magnusbl
magnusbl

Reputation: 809

How do I separate an integer into separate digits in an array in JavaScript?

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!

Upvotes: 80

Views: 234959

Answers (25)

Kenneth Collins
Kenneth Collins

Reputation: 11

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);

Upvotes: 1

Johan Berglund
Johan Berglund

Reputation: 1

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.

Upvotes: 0

Dana Woodman
Dana Woodman

Reputation: 4512

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!

Upvotes: 4

Ivan Vrzogic
Ivan Vrzogic

Reputation: 157

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);

Upvotes: 0

RAGING STAR
RAGING STAR

Reputation: 21

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)

Upvotes: 2

Mark
Mark

Reputation: 1679

Update with string interpolation in ES2015.

const num = 07734;
let numStringArr = `${num}`.split('').map(el => parseInt(el)); // [0, 7, 7, 3, 4]

Upvotes: 0

Creeptosis
Creeptosis

Reputation: 196

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))

Upvotes: 2

Emeeus
Emeeus

Reputation: 5250

It is pretty short using Array destructuring and String templates:

const n = 12345678;
const digits = [...`${n}`];
console.log(digits);

Upvotes: 4

Nick
Nick

Reputation: 51

let input = 12345664
const output = []
while (input !== 0) {
  const roundedInput = Math.floor(input / 10)
  output.push(input - roundedInput * 10)
  input = roundedInput
}
console.log(output)

Upvotes: 1

Adam Kaczmarek
Adam Kaczmarek

Reputation: 146

const number = 1435;
number.toString().split('').map(el=>parseInt(el));

Upvotes: 1

techguy2000
techguy2000

Reputation: 5161

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;
}

Upvotes: 3

Naved Ahmad
Naved Ahmad

Reputation: 821

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('');

Upvotes: 2

Penny Liu
Penny Liu

Reputation: 17408

I ended up solving it as follows:

const n = 123456789;
let toIntArray = (n) => ([...n + ""].map(Number));
console.log(toIntArray(n));

Upvotes: 0

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

Upvotes: -1

Jungdo Lee
Jungdo Lee

Reputation: 1

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);

Upvotes: 0

Alexander
Alexander

Reputation: 473

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]

Upvotes: 22

PDub
PDub

Reputation: 11

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]

Upvotes: 1

Sanjay Shr
Sanjay Shr

Reputation: 2152

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))

Upvotes: 0

Alexey Sukhikh
Alexey Sukhikh

Reputation: 438

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

Upvotes: 5

Dulaj Chathuranga
Dulaj Chathuranga

Reputation: 1

var num = 123456789;
num = num.toString(); //'123456789'
var digits = num.split(""); //[ '1', '2', '3', '4', '5', '6', '7', '8', '9' ]

Upvotes: 0

Nicol&#225;s Fantone
Nicol&#225;s Fantone

Reputation: 2100

What about:

const n = 123456;
Array.from(n.toString()).map(Number);
// [1, 2, 3, 4, 5, 6]

Upvotes: 102

user2521439
user2521439

Reputation: 1425

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)

Upvotes: 27

matthewk
matthewk

Reputation: 1841

Move:

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

above

var j = k / 10;

Upvotes: 0

samccone
samccone

Reputation: 10926

(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

Upvotes: 57

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Why not just do this?

var n =  123456789;
var digits = (""+n).split("");

Upvotes: 107

Related Questions