ECMAScript5 provides a map method for Arrays, applying a function to all elements of an array.
Here is an example:
var a = ['1','2','3']
var result = a.map(function (x) {
return parseInt(x, 10);
});
console.log(result);
See Array.prototype.map()
Answer from dheerosaur on Stack OverflowECMAScript5 provides a map method for Arrays, applying a function to all elements of an array.
Here is an example:
var a = ['1','2','3']
var result = a.map(function (x) {
return parseInt(x, 10);
});
console.log(result);
See Array.prototype.map()
You can do
var arrayOfNumbers = arrayOfStrings.map(Number);
- MDN Array.prototype.map
For older browsers which do not support Array.map, you can use Underscore
var arrayOfNumbers = _.map(arrayOfStrings, Number);
javascript - How to convert an integer into an array of digits - Stack Overflow
How to convert all the items in a String array to Numbers?
How do I separate an integer into separate digits in an array in JavaScript? - Stack Overflow
Convert number into array in Javascript - Stack Overflow
Videos
**** 2019 Answer ****
This single line will do the trick:
Array.from(String(12345), Number);
Example
const numToSeparate = 12345;
const arrayOfDigits = Array.from(String(numToSeparate), Number);
console.log(arrayOfDigits); //[1,2,3,4,5]
Explanation
1- String(numToSeparate) will convert the number 12345 into a string, returning '12345'
2- The Array.from() method creates a new Array instance from an array-like or iterable object, the string '12345' is an iterable object, so it will create an Array from it.
3- In the process of creating this new array, the Array.from() method will first pass any iterable element (ex: '1', '2') to the callback we declare as a second parameter (which is the Number function in this case). This is possible because an String is an "array-like" object.
To make it simpler, we could've declared the callback as:
Array.from(String(numToSeparate), n => Number(n)
4- The Number function will take any string character and will convert it into a number eg: Number('1'); will return 1.
5- These numbers will be added one by one to a new array and finally this array of numbers will be returned.
Summary
The code line Array.from(String(numToSeparate), Number); will convert the number into a string, take each character of that string, convert it into a number and put in a new array. Finally, this new array of numbers will be returned.
I'd go with
var arr = n.toString(10).replace(/\D/g, '0').split('').map(Number);
You can omit the replace if you are sure that n has no decimals.
You cannot split the int, you need to have a string data type for this code to work!
So, I would like to suggest to first split it and then convert it to int as
var numbers = "1, 2, 3";
var eachNumber = numbers.split(",");
/* now parse them or whatso ever */
This will work, as you're just splitting the string. And then you will parse it just the way you did it in the first method (of yours).
var intArray = prompt("...").split(" ").map(Number);