Break a Number Up to an Array of Individual Digits

How do I separate an integer into separate digits in an array in JavaScript?

Why not just do this?

var n =  123456789;
var digits = (""+n).split("");

JavaScript Number Split into individual digits

var number = 12354987,
output = [],
sNumber = number.toString();

for (var i = 0, len = sNumber.length; i < len; i += 1) {
output.push(+sNumber.charAt(i));
}

console.log(output);

/* Outputs:
*
* [1, 2, 3, 5, 4, 9, 8, 7]
*/

UPDATE: Calculating a sum

for (var i = 0, sum = 0; i < output.length; sum += output[i++]);
console.log(sum);

/*
* Outputs: 39
*/

How can I split array of Numbers to individual digits in JavaScript?

You could join the items, split and map numbers.

var array = [ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106],    pieces = array.join('').split('').map(Number);    console.log(pieces);

How to split numbers in an array into single digits

You could join and get a new array.

const
values = [1, 23, 456, 7890],
result = Array.from(values.join(''), Number);

console.log(result);

Splitting integers in arrays to individual digits

int[] test={10212,10202,11000,11000,11010};
ArrayList<Integer> test2 = new ArrayList<Integer>();


for(int i = test.length -1; i >= 0; i--){
int temp = test[i];
while(temp>0){
test2.add(0, temp%10); //place low order digit in array
temp = temp /10; //remove low order digit from temp;
}
}

This will do exactly what you want by placing the lowest order digit of an entry into the "front" of an arraylist, and therefore in front of the previous low order digits/entries.

If you need it to be in an Array, ArrayList has a toArray method.

Splitting an integer in an array into individual digits in Ruby

Change this line:

final_array << ((array[i]) * 2).digits.to_i

By this one:

final_array += ((array[i]) * 2).digits


Related Topics



Leave a reply



Submit