79

This is my code so far:

var n = 123456789;
var d = n.toString().length;
var digits = [];
var squaredDigits = [];
for (i = d; i >= 1; i--) {
    var j = k / 10;
    var r = (n % k / j) - 0.5;
    var k = Math.pow(10, i);
    var result = r.toFixed(); 
    digits.push(result);
}

console.log(digits);

But when I run my code I get this: [9, 1, 2, 3, 4, 5, 6, 7, 8]

If anyone can see the problem or find a better solution I would very much appreciate it!

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
magnusbl
  • 799
  • 1
  • 6
  • 5
  • Does this answer your question? [JavaScript Number Split into individual digits](https://stackoverflow.com/questions/7784620/javascript-number-split-into-individual-digits) – Stefnotch Jul 07 '23 at 20:51

25 Answers25

107

Why not just do this?

var n =  123456789;
var digits = (""+n).split("");
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
100

What about:

const n = 123456;
Array.from(n.toString()).map(Number);
// [1, 2, 3, 4, 5, 6]
Nicolás Fantone
  • 2,055
  • 1
  • 18
  • 24
  • 8
    Nice solution, clear and easy to understand, and makes use of ES6 features. Also one of the recommended features [here](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map?v=control) – tw_hoff Jun 02 '17 at 05:39
  • 8
    `.map(Number)` is very nice! –  Dec 28 '17 at 21:40
  • 2
    By far the best answer – Luiz Henrique Guerra Aug 03 '19 at 01:27
  • 1
    love this solution -- it forces me to do some discovery on global objects and their functionality – rpivovar Sep 06 '19 at 04:29
  • 1
    Could anyone explain why .map(Number) works the way it does? – 4cody Oct 11 '20 at 14:34
  • 1
    @4cody `.map(Number)` applies the `Number` constructor (a function) to each element of the array, which is effectively equivalent to `[Number('1'), Number('2'), ...]` (technically, `[Number('1', 0), Number('2', 1), ...]`, which includes the `index`) . `Number` also knows how to [convert values of other types into numbers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number). – Nicolás Fantone Oct 12 '20 at 21:31
57
(123456789).toString(10).split("")

^^ this will return an array of strings

(123456789).toString(10).split("").map(function(t){return parseInt(t)})

^^ this will return an array of ints

samccone
  • 10,746
  • 7
  • 43
  • 50
  • 1
    This will also give an array of strings.. not numbers – rgthree Mar 28 '12 at 19:25
  • Nice! Just make note that .map isn't available in IE 8 or below. – rgthree Mar 28 '12 at 19:31
  • One would expect `map(parseInt)` to work but `Array.map` calls the function also with the index and the array itself (was it really necessary?) so it won't work. – tokland Dec 17 '12 at 17:03
  • Beware! There’s well known [pitfall](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Tricky_use_case). Yet another `do-not-read-documentation-but-yell-at-stupid-javascript` case. – Bogdan Slovyagin Oct 29 '16 at 11:06
27

I realize this was asked several months ago, but I have an addition to samccone's answer which is more succinct but I don't have the rep to add as a comment!

Instead of:

(123456789).toString(10).split("").map(function(t){return parseInt(t)})

Consider:

(123456789).toString(10).split("").map(Number)
user2521439
  • 1,405
  • 2
  • 13
  • 19
  • 6
    What exactly does the 10 do in ```.toString(10)``` ? I know it references radix 10, but I've tested it with and without and can't find a discernible difference. Thanks! Also, cool edit. – EFH Mar 29 '16 at 00:15
  • @EFH If the radix is not specified, the preferred radix is assumed to be 10. Ref(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) – jtlindsey Jun 30 '16 at 02:01
  • 1
    Just wanted to drop a "amazing solution" here. – Ted Nov 23 '16 at 10:09
  • `.toString(10)` specifies *base 10* numbers. Another example would be .toString(2) which specifies *binary* numbers. Test those two out. – noobninja May 07 '18 at 01:33
  • See also @nicolás-fantone 's ES6-based solution below. `Array.from(n.toString()).map(Number);` – noobninja May 07 '18 at 01:47
21

Modified the above answer a little bit. We don't really have to call the 'map' method explicitly, because it is already built-in into the 'Array.from' as a second argument. As of MDN.

Array.from(arrayLike[, mapFn[, thisArg]])

let num = 1234;
let arr = Array.from(String(num), Number);
console.log(arr); // [1, 2, 3, 4]
Alexander
  • 433
  • 5
  • 8
5

const toIntArray = (n) => ([...n + ""].map(v => +v))
Shota
  • 6,910
  • 9
  • 37
  • 67
Alexey Sukhikh
  • 428
  • 5
  • 8
4

It is pretty short using Array destructuring and String templates:

const n = 12345678;
const digits = [...`${n}`];
console.log(digits);
Emeeus
  • 5,072
  • 2
  • 25
  • 37
4

Assuming the value n:

const n = 123456789

A minimal ES6 version if you'd like:

String(n).split("").map(Number)

An even shorter but less readable version:

[...String(n)].map(Number)

Want to go even shorter (but less readable)?

[...`${n}`].map(Number)

Shorter you say (and basically illegible)!?

[...""+n].map(Number)

Now you're a real programmer, congrats!

Side note

These aren't really efficient (as most in this thread) since you're allocating 2 arrays instead of 1. Want to be more efficient? Try this which only allocates one array:

var arr = []
var str = String(n)
for (var i = 0; i < str.length; i++) {
  arr.push(Number(str[i]))
}

Oldschool but more efficient, huzzah!

Dana Woodman
  • 4,148
  • 1
  • 38
  • 35
2

It's very simple, first convert the number to string using the toString() method in JavaScript and then use split() method to convert the string to an array of individual characters.

For example, the number is num, then

const numberDigits = num.toString().split('');
Naved Ahmad
  • 783
  • 8
  • 7
2

This will work for a number greater than 0. You don't need to convert the number into string:

function convertNumberToDigitArray(number) {
    const arr = [];
    while (number > 0) {
        let lastDigit = number % 10;
        arr.push(lastDigit);
        number = Math.floor(number / 10);
    }
    return arr;
}
techguy2000
  • 4,861
  • 6
  • 32
  • 48
  • thank you!! Was looking for an answer that doesn't convert to string -> array -> array of numbers. This is probably the most performant way, but I guess they would all be O(n) anyways. – Doug May 27 '20 at 10:51
2

You can get a list of string from your number, by converting it to a string, and then splitting it with an empty string. The result will be an array of strings, each containing a digit:

const num = 124124124
const strArr = `${num}`.split("")

OR to build on this, map each string digit and convert them to a Number:

const intArr = `${num}`.split("").map(x => Number(x))
Máté
  • 2,294
  • 3
  • 18
  • 25
Creeptosis
  • 176
  • 1
  • 4
2

Suppose,

let a = 123456

First we will convert it into string and then apply split to convert it into array of characters and then map over it to convert the array to integer.

let b = a.toString().split('').map(val=>parseInt(val))
console.log(b)
  • 2
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Tyler2P Feb 05 '21 at 11:21
1

Here's an alternative to Nicolás Fantone's answer. You could argue it's maybe a little less readable. The emphasis is that Array.from() can take an optional map function as a parameter. There are some performance gains this way since no intermediate array gets created.

const n = 123456;
Array.from(n.toString(), (val) => Number(val)); // [1, 2, 3, 4, 5, 6]
PDub
  • 11
  • 4
1
const number = 1435;
number.toString().split('').map(el=>parseInt(el));
Adam Kaczmarek
  • 146
  • 2
  • 10
  • 1
    Welcome to Stack Overflow! Welcome to Stack Overflow! Please read [what this site is about](https://stackoverflow.com/about) and "[How to answer](https://stackoverflow.com/help/how-to-answer)" before answering a question. – Miroslav Glamuzina May 07 '19 at 12:58
1
let input = 12345664
const output = []
while (input !== 0) {
  const roundedInput = Math.floor(input / 10)
  output.push(input - roundedInput * 10)
  input = roundedInput
}
console.log(output)
Nick
  • 61
  • 1
  • 3
  • I like this answer but I had to add output.reverse() in the end to get the numbers in the correct order as I needed to maintain number positions. – Ahmad Al-Baqawi Apr 11 '20 at 15:35
0
var num = 123456789;
num = num.toString(); //'123456789'
var digits = num.split(""); //[ '1', '2', '3', '4', '5', '6', '7', '8', '9' ]
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Donald Duck May 23 '17 at 11:09
0

It's been a 5+ years for this question but heay always welcome to the efficient ways of coding/scripting.

var n = 123456789;
var arrayN = (`${n}`).split("").map(e => parseInt(e))
Sanjay Shr
  • 2,026
  • 2
  • 16
  • 17
0

Another method here. Since number in Javascript is not splittable by default, you need to convert the number into a string first.

var n = 123;
n.toString().split('').map(Number);
0

I ended up solving it as follows:

const n = 123456789;
let toIntArray = (n) => ([...n + ""].map(Number));
console.log(toIntArray(n));
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
0

Update with string interpolation in ES2015.

const num = 07734;
let numStringArr = `${num}`.split('').map(el => parseInt(el)); // [0, 7, 7, 3, 4]
Mark
  • 1,610
  • 1
  • 14
  • 27
0
var n = 38679;
var digits = n.toString().split("");
console.log(digits);

Now the number n is divided to its digits and they are presented in an array, and each element of that array is in string format. To transform them to number format do this:

var digitsNum = digits.map(Number);
console.log(digitsNum);

Or get an array with all elements in number format from the beginning:

var n = 38679;
var digits = n.toString().split("").map(Number);
console.log(digits);
Ivan Vrzogic
  • 157
  • 1
  • 8
0

This is actually the cleanest solution I think.

  var n =  123456789;
  const digits = (`${n}`).split('')

You put it in a string literal but it is kept as numbers, and then it is split to an array and assigned to digits.

0

split, then looped over to square

here the numbers are split, then squared.

const n = 123456;
const numArr = Array.from(n.toString());

for (let i = 0; i < numArr.length; i++) {
  numArr[i] = `${numArr[i]**2}`;
}

console.log(numArr);
0

Move:

var k = Math.pow(10, i);

above

var j = k / 10;
matthewk
  • 1,841
  • 17
  • 31
-1

const toIntArray = (n) => ([...n + ""].map(v => +v))