Splitting a number into an array - javascript

Alright so I'm trying to completely split a number into an Array. So for example:
var num = 55534;
var arr = []; <- I would want the Array to look like this [5,5,5,3,4]
Basically i want to to completely split the number apart and place each Number into its own element of the array. Usually in the past i would just convert the number into a string then use the .split() function. This is how i use to do it:
num += "";
var arr = num.split("");
But this time i actually need to use these numbers, so they can not be strings. What would you guys say be the way of doing this?
Update, after the edit for some reason my code is crashing every run:
function DashInsert(num) {
num += "";
var arr = num.split("").map(Number); // [9,9,9,4,6]
for(var i = 0; i < arr.length; i++){
if(arr[i] % 2 === 1){
arr.splice(i,0,"-");
}// odd
}
return arr.join("");
}

String(55534).split("").map(Number)
...will handily do your trick.

You can do what you already did, and map a number back:
55534..toString().split('').map(Number)
//^ [5,5,5,3,4]

I'll do it like bellow
var num = 55534;
var arr = num.toString().split(''); //convert string to number & split by ''
var digits = arr.map(function(el){return +el}) //convert each digit to numbers
console.log(digits); //prints [5, 5, 5, 3, 4]
Basically I'm converting each string into numbers, you can just pass Number function into map also.

Related

Elegant way to split hex string at byte 00?

I need to split a hex string at every 00 byte. I tried this:
string.split('00');
But that causes splits at 5009, for instance, which is incorrect because it is splitting a byte in half.
In other words, it turns 5009 to [5, 9], which I don't want. But I do want it to turn af0059 to [af, 59].
Is it even possible to split bytes using regex, without cutting any bytes in half?
I could use a loop to seek through the string and only divide the string at even-number indices, but I would much prefer a regex expression.
Because of the byte sizes, you need to first split the string into byte-sizes, then map and finally join.
const string = "af00b9e00f70";
const res = string.split(/([\d\w]{4})/).filter(e => e).map(e => e.replace(/00([\d\w]{2})/, "$1").replace(/([\d\w]{2})00/, "$1")).join("");
console.log(res);
Here's a somewhat "old school' approach, but it demonstrates the principal. I say "old school' because we had to do this all the time back in the days of assembler coding. 'string' contains your long string of hex pairs (bytes). Here I convert it to byte values. Change the 'string' to whatever you want, but be sure it has an even number of hex digits. Call 'translate' to demonstrate it, and format the output into an alert() (or just output to the console)
var values = []; // output array
var string = "000102030405060708090a0b0c0d0e0f1FFFFEFDFCFBFAF9F8F7F6F5F4F3F2F0";
function getHexByteValues( string) {
var hex= "0123456789ABCDEF";
var outIx=0;
for (var i =0; i <= (string.length-2); i +=2) { // skip every other
//get higher and lower nibble
var hexdig1 = string.substring(i, i+1);
var hexdig0 = string.substring(i+1, i+2);
// for simplicity, convert alpha to upper case
hexdig1 = hexdig1.toUpperCase();
hexdig0 = hexdig0.toUpperCase();
// convert hex to decimal value.
// position in lookup string == value
var dec1 = hex.indexOf(hexdig1);
var dec0 = hex.indexOf(hexdig0);
// calc "byte" value, and add to values.
values[outIx++] = dec1 * 16 + dec0;
}
}
function translate(string) {
getHexByteValues(string);
var output="";
for (var i =0; i < values.length; i++) {
output += i + " = " + values[i] + "\r\n";
}
alert (output);
}
Maybe not the most elegant, but it works
const inp = "af00b9e00f70"
const out = inp.match(/.{1,2}/g).map(a=>a=="00"?"_":a).join("").split("_");
console.log(out);

How to make a single string into a multitude of strings?

I have a string called e3 which holds the string 1,2,4,5,3,6. I want to add up all of those numbers up to make the number 21 I was considering doing a for loop for this however I do not know how to turn part of a string into its own value.
I anyone has any better idea of what to do please comment, or answer.
You could use String#split for the string and use Array#reduce for summing.
var e3 = '1,2,4,5,3,6',
sum = e3.split(',').reduce(function (a, b) {
return a + +b; // +b forces b to number
}, 0);
console.log(sum);
If you are sure that it is always a comma separated list of numbers, you could split it on the comma into an array and then use array.reduce() to sum them
var asString = '1,2,4,5,3,6';
var asArray = asString.split(',');
var total = asArray.reduce(function(prev, current){
return prev + parseInt(current, 10);
}, 0);
console.log(total) // outputs 21;
You can do it like this:
var e3 = "1,2,4,5,3,6";
// Split by separator ','
var stringsArr = e3.split(',');
var sum = 0;
// Loop through array of string numbers
stringsArr.forEach(function(str) {
// get Int from a string
var strVal = parseInt(str, 10);
sum += strVal;
});
here's the fiddle
Here is working code to do what you need: https://plnkr.co/edit/8LSkZi0oC8msbHI0qOrz?p=preview
At first you use the split method - this separates a string into an array of strings, based on some separator value. In our case, the separator is a comma, but it could be a blank space or something else:
var testString = '1,2,4,5,3,6';
var separator = ',';
function splitStringOnCommasAndGetArray(string, separator){
var arrayOfStrings = string.split(separator);
return arrayOfStrings;
}
After that, we loop through the array and turn each value into a number. We add the numbers, like so:
function addUpArray(arrayOfStrings){
var totalNumber = 0;
for(var i = 0; i < arrayOfStrings.length; i++){
var currentNum = parseInt(arrayOfStrings[i]);
console.log(currentNum);
totalNumber += currentNum;
}
return totalNumber;
}

Javascript Split Method with Additive Persistence

This is my first Stack Overflow post, so please let me know if I am not formatting properly!
I am trying to answer this Coderbyte question:
"Using the JavaScript language, have the function AdditivePersistence(num) take the num parameter being passed which will always be a positive integer and return its additive persistence which is the number of times you must add the digits in num until you reach a single digit. For example: if num is 2718 then your program should return 2 because 2 + 7 + 1 + 8 = 18 and 1 + 8 = 9 and you stop at 9."
However, my solution keeps returning "str.split is not a function". I thought that was a standard method for converting strings into arrays. Any idea why this code might not work?
function AdditivePersistence(num) {
let str = num.toString; //number into string
let arr = str.split(""); //string into array
// adds numbers in array, then repeats until left with single digit
let count = 0;
while(arr.length > 1) {
arr.reduce(function(a,b){ return Number(a) + Number(b) });
count++;
}
return count;
};
I tried searching Stack Overflow, Google, W3Schools, MDN and other Coderbyte answers but could not figure out why this doesn't work. Any help would be appreciated.
Try using String() constructor.
let str = String(num);
Note also, while loop does not conclude as arr is not redefined by call to .reduce(). You can redefine arr by using String() constructor and .split() again within while loop
function AdditivePersistence(num) {
let str = String(num); //number into string
let arr = str.split(""); //string into array
// adds numbers in array, then repeats until left with single digit
let count = 0;
while (arr.length > 1) {
// set `arr` to string then array with values returned from `.reduce()`
arr = String(arr.reduce(function(a, b) {
return Number(a) + Number(b)
})).split("");
count++;
}
return count;
};
var n = AdditivePersistence(2718);
console.log(n);
You can convert to string this way:
let str = num + '';

How to build a binary-array from hex strings

I'm new to the concept of working with data on the binary level and am hoping someone can give me a hand here...
I'd like to build a binary buffer out of a series of hex numbers that are represented as strings.
For example,
suppose I have "xFCx40xFF" and I want to turn this into an array that looks like: 111111000100000011111111.
What's the best way to do this?
My best attempt seems to not be working:
var raw = "xFCx40xFF"
var end = raw.length-2;
var i = 1;
var j = 0;
var myArray = new Uint8Array(raw.len);
while (i < end) {
var s = raw.substr(i,2);
var num = parseInt(s,16);
i += 3;
myArray[j] = num;
j += 8;
}
Each 3 characters in string will represent 1 number in Uint8Array. Each number in Uint8Array will represent 8 bits. Your code was creating Uint8Array larger than needed and then placing values are wrong locations.
I have simplified the code to use a singe index i which represents the location in the Uint8Array. Corresponding location in string can be easily computed from i.
var raw = "xFCx40xFF"
var myArray = new Uint8Array(raw.length / 3);
for (var i = 0; i < raw.length / 3; i++) {
var str = raw.substr(3 * i + 1, 2);
var num = parseInt(str, 16);
myArray[i] = num;
}
Remove the 'x' character of your hex string and call parseInt() with the radix 16 and toString() with the radix 2 to get the binary string.
var raw = "xFCx40xFF";
var bin = parseInt(raw.split('x').join(''), 16).toString(2);
document.body.textContent = bin;
and if you need an array, just add .split('') at the end.
parseInt(raw.split('x').join(''), 16).toString(2).split('');
or iterate through each character.

how to make string as array in java script?

I have a string value like:
1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i
I need to convert it into array in JavaScript like
1 2 3
4 5 6
7 8 9
etc.
Can any one please suggest me a way how to do this?
You are looking for String.split. In your case, you need to split twice. Once with ; to split the string into chunks, then separately split each chunk with , to reach the array structure you are looking for.
function chunkSplit(str) {
var chunks = str.split(';'), // split str on ';'
nChunks = chunks.length,
n = 0;
for (; n < nChunks; ++n) {
chunks[n] = chunks[n].split(','); // split each chunk with ','
}
return chunks;
}
var arr = chunkSplit("1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i");
If you need a multi-dimensional array you can try :
var array = yourString.split(';');
var arrCount = array.length;
for (var i = 0; i < arrCount; i++)
{
array[i] = array[i].split(',');
}
Try the following:
var yourString = '1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i';
var array = [];
yourString.split(';').forEach(function(value) {
array.push(value.split(','));
});
jsFiddle Demo
Note: .forEach() not supported in IE <=8
The following split command should help:
yourArray = yourString.split(";");

Categories

Resources