0

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?

3
  • 2
    Try this interget .toString().split('').map(e => parseInt(e)) Commented May 25, 2020 at 4:39
  • 1
    Does this answer your question? How to convert an integer into an array of digits Commented May 25, 2020 at 4:42
  • @visibleman Yes. I was forgetting to add the word digit to my google search. Thanks for the help Commented May 25, 2020 at 4:43

2 Answers 2

2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

2

Or you can do it like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.