1

What is the shortest way of creating an array consisting of digits from a number?

I don't want to revert to declaring an empty array and then iterating over the number via the for(a,b,c) loop.

I would like something more declarative. Ideally, something like:

Array.from(143) // => [1, 4, 3]
Bahman Parsa Manesh
  • 2,314
  • 3
  • 16
  • 32
Andrey Mikhaylov - lolmaus
  • 23,107
  • 6
  • 84
  • 133
  • 1
    This is not about code golf, I do not want to sacrifice readability, maintainability and scalability in favor of shortness. On the opposite, I would like to improve readability by getting rid of imperative code that requires brain strain to grasp. – Andrey Mikhaylov - lolmaus Aug 02 '18 at 06:07
  • Then... just define a function `toDigits`. What you do inside the function doesn't matter. – user202729 Aug 02 '18 at 06:08

6 Answers6

6

Turn the number into a string, split the string, and turn each character into a number:

const arr = String(143)
  .split('')
  .map(Number);
console.log(arr);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

You could use Array.from with the stringed number and Number as mapping function.

Array.from takes an iterable and creates an array. It takes a supplied mapping function and returns a new array with values after using the callback or raw values.

var number = 143,
    array = Array.from(number.toString(), Number);
    
console.log(array);
Stanislav Kvitash
  • 4,614
  • 18
  • 29
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Convert to string then split then map:

const num = 210; 
const numArray = ("" + num).split("").map(Number)
dorintufar
  • 660
  • 9
  • 22
1

As for Array.from usage, using map to cast from string to integer.

Step 1: change 143 to "143" by String(143).

Step 2: change "143" to ["1", "4", "3"] by Array.from("143").

Step 3: while pass Number function as second parameter in Array.from, will change the result of ["1", "4", "3"] to [1, 4, 3] . Which 'Number' will be used as map function to iterate every element with it.

Code example:

var intArray = Array.from(String(143), Number);
console.log(intArray);

Update

Array.from already has map function as its second parameter.

Terry Wei
  • 1,521
  • 8
  • 16
0

Convert the number to string, split the string then convert each element of the array to Number using map:

var num = 143;
var splitedNum = num.toString().split('').map(Number);
console.log(splitedNum)
BlackBeard
  • 10,246
  • 7
  • 52
  • 62
0

Try this

var n = 143;
var arr = n.toString(10).replace(/\D/g, '0').split('').map(Number);
console.log(arr)
Saboor
  • 352
  • 1
  • 10