flyKite
flyKite

Reputation: 15

Convert numbers to arrays

Question for javascript, why do we need to convert numbers to string then only it can be converted to arrays?

const numbers =12345;
const stringNumbers = numbers.toString();
const array =[];

for(let i = 0 ; i < stringNumbers.length; i++){
    array.push(stringNumbers[i]);
}

["1", "2", "3", "4", "5"]

Upvotes: 1

Views: 43

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522007

In your current approach, you are simply iterating over the characters of the number string, and inserting them into the array one by one. Well, that of course necessitates that the number first be converted into a string. Here is an approach which avoids the string conversion entirely:

var numbers = 12345;
var array = [];

while (numbers > 0) {
    array.push(numbers % 10);
    numbers = Math.floor(numbers / 10);
}
array = array.reverse();

console.log(array);

Upvotes: 1

Related Questions