Ian Halstead
Ian Halstead

Reputation: 98

How can I create an array from each number in an array?

I have an integer and want to create an array from each of its numbers.

let interget = 345;
//I want create the array [3,4,5]

Is there any easy way to do this using Array.from() or would I need to convert the number to a string first?

Upvotes: 0

Views: 99

Answers (2)

Rajneesh
Rajneesh

Reputation: 5308

Or you can do it like this:

var result = Array.from('345', Number)
console.log(result);

Upvotes: 2

ashish singh
ashish singh

Reputation: 6904

easy way by converting to string

(inputNumber + "").split("").map(char => +char)

basically we split string and convert each character back to number


doing it manually

function getDigits(n) {
  const ans = [];
  while(n > 0){
    let digit = n % 10;
    ans.push(digit);
    n -= digit;
    n /= 10;
  }

  return ans.reverse();
}

Upvotes: 2

Related Questions