[javascript] 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!

This question is related to javascript arrays digits

The answer is


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

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

It is pretty short using Array destructuring and String templates:

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


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

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]

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

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


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

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]

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

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

(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


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


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

What about:

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

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)

Update with string interpolation in ES2015.

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

Move:

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

above

var j = k / 10;

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)

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

I ended up solving it as follows:

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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to digits

C++ - how to find the length of an integer Gets last digit of a number Sum the digits of a number Get number of digits with JavaScript How do I separate an integer into separate digits in an array in JavaScript? C: how to break apart a multi digit number into separate variables? Show a leading zero if a number is less than 10 How to tell if string starts with a number with Python? in python how do I convert a single digit number into a double digits string? Controlling number of decimal digits in print output in R