JavaScript Number Split into individual digits - javascript

I am trying to solve a math problem where I take a number e.g. 45, or 111 and then split the number into separate digits e.g. 4 5 or 1 1 1. I will then save each number to a var to run a method on. Does anyone know how to split a number into individual digitals?
For example I have a loop that runs on an array :
for (var i = 0; i < range.length; i++) {
var n = range[i];
}
For each number, I would like to split its digits and add them together?

var num = 123456;
var digits = num.toString().split('');
var realDigits = digits.map(Number)
console.log(realDigits);

var number = 12354987,
output = [],
sNumber = number.toString();
for (var i = 0, len = sNumber.length; i < len; i += 1) {
output.push(+sNumber.charAt(i));
}
console.log(output);
/* Outputs:
*
* [1, 2, 3, 5, 4, 9, 8, 7]
*/
UPDATE: Calculating a sum
for (var i = 0, sum = 0; i < output.length; sum += output[i++]);
console.log(sum);
/*
* Outputs: 39
*/

You can also do it in the "mathematical" way without treating the number as a string:
var num = 278;
var digits = [];
while (num != 0) {
digits.push(num % 10);
num = Math.trunc(num / 10);
}
digits.reverse();
console.log(digits);
One upside I can see is that you won't have to run parseInt() on every digit, you're dealing with the actual digits as numeric values.

This is the shortest I've found, though it does return the digits as strings:
let num = 12345;
[...num+''] //["1", "2", "3", "4", "5"]
Or use this to get back integers:
[...num+''].map(n=>+n) //[1, 2, 3, 4, 5]

I will provide a variation on an answer already given so you can see a different approach that preserves the numeric type all along:
var number = 12354987,
output = [];
while (number) {
output.push(number % 10);
number = Math.floor(number/10);
}
console.log(output.reverse().join(',')); // 1,2,3,5,4,9,8,7
I've used a technique such as the above to good effect when converting a number to Roman numerals, which is one of my favorite ways to begin to learn a programming language I'm not familiar with. For instance here is how I devised a way to convert numbers to Roman numerals with Tcl slightly after the turn of the century: http://code.activestate.com/recipes/68379-conversion-to-roman-numerals/
The comparable lines in my Tcl script being:
while {$arabic} {
set digit [expr {$arabic%10}]
set arabic [expr {$arabic/10}]

// Split positive integer n < 1e21 into digits:
function digits(n) {
return Array.from(String(n), Number);
}
// Example:
console.log(digits(1234)); // [1, 2, 3, 4]

You can work on strings instead of numbers to achieve this. You can do it like this
(111 + '').split('')
This will return an array of strings ['1','1','1'] on which you can iterate upon and call parseInt method.
parseInt('1') === 1
If you want the sum of individual digits, you can use the reduce function (implemented from Javascript 1.8) like this
(111 + '').split('').reduce(function(previousValue, currentValue){
return parseInt(previousValue,10) + parseInt(currentValue,10);
})

Use String, split and map :
String(number).split("").map(Number);
function splitNum(num) {
return String(num).split("").map(Number);
}
console.log(splitNum(1523)); // [1, 5, 2, 3]
console.log(splitNum(2341)); // [2, 3, 4, 1]
console.log(splitNum(325)); // [3, 2, 5]

Without converting to string:
function toDigits(number) {
var left;
var results = [];
while (true) {
left = number % 10;
results.unshift(left);
number = (number - left) / 10;
if (number === 0) {
break;
}
}
return results;
}

Using String, ... and map
const num = 7890;
const digits = [...String(num)].map(Number);
console.log(digits)
Alternatively, using ... and reduce to get digits and their sum.
const sumOfDigits = num => [...""+num].reduce((acc, dig) => acc + +dig, 0);
console.log('Sum of digits: ', sumOfDigits(7890));

Separate each 2 parametr.
function separator(str,sep) {
var output = '';
for (var i = str.length; i > 0; i-=2) {
var ii = i-1;
if(output) {
output = str.charAt(ii-1)+str.charAt(ii)+sep+output;
} else {
output = str.charAt(ii-1)+str.charAt(ii);
}
}
return output;
}
console.log(separator('123456',':')); //Will return 12:34:56

With ES6, you could use Array.from with a stringed number as iterables and Number as mapping function.
const getDigits = n => Array.from(n.toString(), Number);
console.log(getDigits(12345));

A fun introduction to recursion. This answer takes a Number and returns an array of Number digits. It does not convert the number to a string as an intermediate step.
Given n = 1234,
n % 10 will return first (right-moist) digit, 4
n / 10 will return 123 with some remainder
Using Math.floor we can chop the remainder off
Repeating these steps, we can form the entire result
Now we just have to build the recursion condition,
If the number is already a single digit (n < 10), return an array singleton of the digit
otherwise (inductive) the number is 10 or greater; recur and prepend to the first digit
const digits = (n = 0) =>
n < 10
? [ n ]
: [ ... digits (Math.floor (n / 10)), n % 10 ]
console.log (digits ()) // [ 0 ]
console.log (digits (1)) // [ 1 ]
console.log (digits (12)) // [ 1, 2 ]
console.log (digits (123)) // [ 1, 2, 3 ]
console.log (digits (11234)) // [ 1, 2, 3, 4 ]
console.log (digits (123456789012))
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2 ]

This also works:
var number = 12354987;
console.log(String(number).split('').map(Number));

Shadow Wizard , extended version by Orien
var num:Number = 1523;
var digits:Array = [];
var cnt:int = 0;
while (num > 0) {
var mod:int = num % 10;
digits.push(mod * Math.pow(10, cnt))
num = Math.floor(num / 10);
cnt++;
}
digits.reverse();
trace(digits);
output:1000,500,20,3

A functional approach in order to get digits from a number would be to get a string from your number, split it into an array (of characters) and map each element back into a number.
For example:
var number = 123456;
var array = number.toString()
.split('')
.map(function(item, index) {
return parseInt(item);
});
console.log(array); // returns [1, 2, 3, 4, 5, 6]
If you also need to sum all digits, you can append the reduce() method to the previous code:
var num = 123456;
var array = num.toString()
.split('')
.map(function(item, index) {
return parseInt(item);
})
.reduce(function(previousValue, currentValue, index, array) {
return previousValue + currentValue;
}, 0);
console.log(array); // returns 21
As an alternative, with ECMAScript 2015 (6th Edition), you can use arrow functions:
var number = 123456;
var array = number.toString().split('').map((item, index) => parseInt(item));
console.log(array); // returns [1, 2, 3, 4, 5, 6]
If you need to sum all digits, you can append the reduce() method to the previous code:
var num = 123456;
var result = num.toString()
.split('')
.map((item, index) => parseInt(item))
.reduce((previousValue, currentValue) => previousValue + currentValue, 0);
console.log(result); // returns 21

I used this simple way of doing it.
To split digits
var N = 69;
var arr = N.toString().split('').map(Number)
// outputs [6,9]
console.log( arr );
To add them together
console.log(arr.reduce( (a,b) => a+b )); // 15

And the easiest.... num_string.split('').map(Number)
Try below:
console.log((''+123).split('').map(Number))

To just split an integer into its individual digits in the same order, Regular Expression is what I used and prefer since it prevents the chance of loosing the identity of the numbers even after they have been converted into string.
The following line of code convert the integer into a string, uses regex to match any individual digit inside the string and return an array of those, after which that array is mapped to be converted back to numbers.
const digitize = n => String(n).match(/\d/g).map(Number);

I might be wrong, but a solution picking up bits and pieces. Perhaps, as I still learning, is that the functions does many things in the same one. Do not hesitate to correct me, please.
const totalSum = (num) => [...num + ' '].map(Number).reduce((a, b) => a + b);
So we take the parameter and convert it to and arr, adding empty spaces. We do such operation in every single element and push it into a new array with the map method. Once splited, we use reduce to sum all the elements and get the total.
As I said, don't hesitate to correct me or improve the function if you see something that I don't.
Almost forgot, just in case:
const totalSum = (num) => ( num === 0 || num < 0) ? 'I need a positive number' : [...num + ' '].map(Number).reduce((a, b) => a + b);
If negatives numbers or just plain zero go down as parameters. Happy coding to us all.

I am posting this answer to introduce the use of unshift which is a modern solution. With push, you add to the end of an array while unshift adds to the beginning. This makes the mathematical approach more powerful as you won't need to reverse anymore.
let num = 278;
let digits = [];
while (num > 0) {
digits.unshift(num % 10);
num = parseInt(num / 10);
}
console.log(digits);

var num = 111,
separateDigits = num.toString().split(""), i, l = separateDigits.length;
for( i = 0; i < l; ++i ) {
someObject.someMethod( +separateDigits[i] );
}

You can try this.
var num = 99;
num=num.toString().split("").map(value=>parseInt(value,10)); //output [9,9]
Hope this helped!

function iterateNumber(N, f) {
let n = N;
var length = Math.log(n) * Math.LOG10E + 1 | 0;
for (let i = 0; i < length; i++) {
const pow = Math.pow(10, length - i - 1)
let c = (n - (n % pow)) / pow
f(c, i)
n %= pow
}
}

('' + 123456789).split('').map( x => +x ).reduce( (a,b) => a+b ) === 45
true
or without map
('' + 123456789).split('').reduce( (a,b) => (+a)+(+b) ) === 45
true

You can do it in single line, seperate each digits than add them together :
var may = 12987;
var sep = (""+may).split("").map(n=>+n).reduce((a,b)=>a+b);

This is my short solution.. with sum of number
function sum (num) {
let sNumber = num
.toString()
.split('')
.reduce((el1, el2) => {
return Number(el1) + Number(el2)
}, 0)
return sNumber
}
console.log(sum(123))
console.log(sum(456))

javascript has a function for it and you can use it easily.
console.log(new Intl.NumberFormat().format(number));
for example :
console.log(new Intl.NumberFormat().format(2334325443534));
==> 2,334,325,443,534

Iterate through each number with for...of statement.
By adding a + sign before a String, it will be converted into a number.
const num = 143,
digits = [];
for (const digit of `${num}`) {
digits.push(+digit)
}
console.log(digits);
Inspired by #iampopov You can write it with spread syntax.
const num = 143;
const digits = [...`${num}`].map(Number);
console.log(digits);

And as a one liner.
console.log(Number.MAX_SAFE_INTEGER.toString().split('').reduce((pv, v) => Number(v) + pv, 0));

Related

Javascript: Plus one challenge

You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
My solution:
/**
* #param {number[]} digits
* #return {number[]}
*/
var plusOne = function(digits) {
let num = Number(digits.join('')) + 1
const myFunc = x => Number(x);
digits = Array.from(String(num), myFunc)
return digits
};
console.log(plusOne([1,2,3,5,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7]));
Why does the above code not work given the following argument:
[1,2,3,5,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7]
my output:
[1,NaN,2,3,5,6,7,7,7,7,7,7,7,7,7,7,7,7,NaN,NaN,2,1]
expected output:
[1,2,3,5,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8]
Since your number is larger then MAX_SAFE_INTEGER, I'd convert the array to a BigInt so you can add 1 to that (++), this way a 9 will be converted to the expected 10
After that, use the same technique to convert it back to an array:
var plusOne = function(digits) {
let bigInt = BigInt(digits.join(''));
bigInt++;
return Array.from(bigInt.toString(), Number);
};
console.log(plusOne([1,2,3,5,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7]));
// [ 1, 2, 3, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8 ]
This can be re-written as a fancy one-liner like so:
const plusOne = (digits) => Array.from((BigInt(digits.join('')) + 1n).toString(), Number);
Here is a implementation.
var plusOne = function (digits) {
let carry = 0;
let arr = [];
for (let i = digits.length - 1; i >= 0; i--) {
let n = Number(digits[i]);
if (i === digits.length - 1) {
n = n + 1;
} else if (carry === 1) {
n = n + 1;
}
if (n === 10) {
carry = 1;
n = 0;
}
arr.push(n)
}
return arr.reverse();
};
Looks like someone else already gave basically the same answer as I typed this, but here's my answer anyway.
It looks like you're getting this error, because the Number(digits.join('')) + 1 returns 1.2356777777777777e+21. Running Array.from(String(1.2356777777777777e+21)) by itself returns [1,.,2,3,5,6,7,7,7,7,7,7,7,7,7,7,7,7,e,+,2,1]. Notice you have 3 NaN values at positions 1, 18, and 19. In other words, you can't convert ".", "+", or "+" to numbers with Number(). It just returns NaN, as they are Not a Number...
Long story short—unless I misunderstand the point in the original question—you're going about it all wrong. Because your number is so big, you should use the BigInt() object. Note: It can only operate with other BigInts. Here's a working example:
const plusOne = digits => {
const num = BigInt(digits.join('')) + BigInt(1)
return num.toString().split('')
}
console.log(plusOne([1,2,3,5,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7]))
I hope that helps.

Find lowest positive integer that does not appear in array

I am trying to solve a leetcode type problem that is a practice problem that came with an upcoming code test I need to do for a job and I am having trouble with it. Can anyone help me understand whats going wrong?
I am essentially looking for the brute force option as I dont know algos/DS.
PROBLEM:
Write a function:
function solution(A);
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the function should return 1.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [−1,000,000..1,000,000].
HERE IS MY SOLUTION:
function solution(A) {
let newArray = A.sort(function(a, b){return a-b})
let lowestNumber = 1
for(i=0; i < newArray.length; i++) {
if(lowestNumber > newArray[0]) {
return lowestNumber
}
if(lowestNumber == newArray[i]) {
lowestNumber = lowestNumber + 1
}
if(i = newArray.length - 1) {
return lowestNumber
}
}
}
The below snippet isnt working like I expect it to. lowestNumber isnt being increased and also the loop is exiting here I believe.
if(lowestNumber == newArray[i]) {
lowestNumber = lowestNumber + 1
Thanks for your help!
You can do this in O(N) using a Map():
First set every number in the array.
Then starting from 1 look for and return the missing number in the sequence.
function solution(arr) {
const seen = new Map();
for (let i = 0; i < arr.length; i++) {
seen.set(arr[i]);
}
for (let i = 1; i <= arr.length + 1; i++) {
if (!seen.has(i)) return i;
}
return 1;
}
console.log(solution([1, 3, 6, 4, 1, 2])); //-> 5
console.log(solution([1, 2, 3])); //-> 4
console.log(solution([-1, -3])); //-> 1
I think your > should be <, and the = in if(i = newArray.length - 1) should be ===.
And lowestNumber > newArray[0] will always be true if the array contains a negative number, so 1 will be returned.
Your effort seems careless, so you are going to have to up your game for the interview.
const integers = [5, -345, 562456, 95345, 4, 232, 1, 2, 3, 7, -457];
function solution(A) {
let newArray = A.sort((a, b) => a - b);
let lowestNumber = 1;
for (let i = 0; i < newArray.length; i++) {
const n = newArray[i];
if (n > 0) {
if (lowestNumber < n) {
return lowestNumber;
} else {
lowestNumber = n + 1;
}
}
}
return lowestNumber;
}
console.log(solution(integers));
The fastest solution
function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
if (!A) return 1;
A.sort();
if (A[A.length - 1] < 1) return 1;
const setA = new Set(A);
let length = setA.size;
for (let i = 1; i <= length; i++) {
if (!setA.has(i)) {
return i;
}
}
return length + 1;
}
I have worked same problem for nowadays, and regardless the original answer, here is my version of finding least positive number which is missing the in the array.
function findLeastPositive(array) {
const numbersSet = new Set(array);
let leastPositiveNumber = 1;
while(numbersSet.has(leastPositiveNumber)) {
leastPositiveNumber++;
}
return leastPositiveNumber;
}
let result = findLeastPositive([1,2,3,4,5,6,7,8,9,0]);
console.log(result);
result = findLeastPositive([10,11,12,13,14,15,16,17,18,19]);
console.log(result);
There are sure similar answers floating on the internet but using given array length disturbing me of which I can't explain properly why we have to create second loop starts with 1 (known the least positive number) and to N.
Using hash table (I am using Set here) for lookup table is fine idea, as in it effect to overall performance O(N) (probably initialize the Set with array) and O(1) for checking if the value in the Set or not.
Then we need to set second loop for obvious reason that checking the the smallest positive number existence, starting from 1..N range. This is the part bugged me, so I decided to go for while loop. It's obvious rather why there's a for..loop starts from 1..N on which N is the length of the array.
Here is 100% code
function solution(A) {
/**
* create new array of positive numbers in given array,
* if there sis no specific number in given array, in result array
* that index will be undefine
*/
const c = A.reduce((arr, cur) => {
if(cur > 0) arr[cur] = 1;
return arr;
} , [1] )
/**
* return first undefined index
*/
for(let i = 0; i < c.length; i++)
if(!c[i]) return i;
// otherwise return the maximum index in array
return c.length;
}
function solution(arr) {
for (let i = 1; i <= arr.length + 1; i++) {
if (!arr.includes(i)) return i;
}
return 1;
}
console.log(solution([1, 3, 6, 4, 1, 2])); //-> 5
console.log(solution([1, 2, 3])); //-> 4
console.log(solution([-1, -3])); //-> 1

JS get max first n values from a string

I need to capture maximum 5 elements of a string. However if there are less than 5, then I just need how many there are there.
var y = '1,2,3,4,5,6,7,8,9,10'
//desired result:
var out = '1,2,3,4,5' // please note there is no trailing comma
var y = '1,2,3'
//desired result:
var out = '1,2,3'
My code:
for (var i = 0; i < 5; i++) {
x += y;
x = x + ",";
}
Write(x);
A simple method will do. The below splits the string by , then takes either n elements or the total length if it is less than n and then rejoins the values with a comma
const getNValues = (str, n) => {
const values = str.split(",");
const res = values.slice(0, Math.min(values.length,n))
return res.join(",");
}
console.log(getNValues("1,2,3,4,5,6,7,8,9",5));
console.log(getNValues("1,2,3",5));
Try this simple function to do that
function getMaxLen(str) {
if(typeof str != 'string') return null;
str = str.split(',');
return str.slice(0, 5).join(',');
}
console.log(getMaxLen('1,2,3,4,5,6,7,8,9,10'))
console.log(getMaxLen('1,2,3'))
var string = '1, 2, 3, 4, 5, 6, 7, 8, 9, 10';
var out = (string.match(/^([0-9],? ?){0,5}/)[0] || '').replace(/, ?$/, '');
console.log(out)
[EDIT] Explanation
.match(^([0-9],? ?){0,5}/g):
start at the begging ^
match numbers [0-9]
then a comma if any and a space if any ,? ?.
match this expression 0 to 5 times {0, 5}

Javascript - Function for each which sums and multiplies every int in array

Javascript is something new for me, and we have to do homework.
I have created new array:
var numbers = [1,2,3,4,5,6];
And with function forEeach I should achieve result like in console.log:
console.log(numbers[0]*numbers[1]+numbers[0]+numbers[1]);
I've tested many things, but I don't have any idea how to pull out signle init...
I know it should be simple, but I've stucked.
Thanks for help!
From your question looks like your problem is interacting with the current element of the forEach loop.
var numbers = [1,2,3,4,5,6]
// this will print every number in the array
// note that index numbers are not needed to get elements from the array
numbers.forEach(function(num){
console.log(num)
})
Now, if what you're trying t achieve is sum and multiply every int (as stated in the question title), you could do it like this
var numbers = [1,2,3,4,5,6]
var sumResult = 0
var multiplicationResult = 1
// the function will be evaluated for every element of the array
numbers.forEach(function(num){
sumResult += num
multiplicationResult *= num
})
console.log('Sum', sumResult)
console.log('Multiplication', multiplicationResult)
However, a more appropiate approach could be obtained by using reduce like this:
var numbers = [1,2,3,4,5,6]
var sumResult = numbers.reduce(function(result, num){
return num+result
}, 0)
var multiplicationResult = numbers.reduce(function(result, num){
return num*result
}, 1)
console.log('Sum', sumResult)
console.log('Multiplication', multiplicationResult)
Hope this helps.
More info:
Reduce # MDN
ForEach # MDN
To pull out a single number for the provided array you using the indexer/bracket notation which is specifying a number (length of array - 1) in brackets, like below:
var numbers = [1, 2, 3, 4, 5, 6];
numbers[0]; // selects the first number in the array
numbers[1]; // selects second number etc.
To sum up the numbers using forEach, simply do:
var sum = 0;
numbers.forEach(function(number) {
sum += number; // add number to sum
});
forEach goes through all the numbers in the numbers array, passing in each number to the function defined and then adds the number to the sum variable.
If you want your results, use map(). Unlike forEach(), map() will always return results in a new array. It wasn't very clear as to what expression you are expected to use or what the result of said expression should be so this demo will do the following on each iteration:
A = current value * next value
B = current value + next value
C = A + B;
Demo
const num = [1, 2, 3, 4, 5, 6];
let arr = num.map(function(n, idx, num) {
let next = num[idx + 1];
if (!next > 0) {
next = idx + 2;
}
let subSUM = n + next;
let subPRD = n * next;
let subRES = subPRD + subSUM;
return subRES;
});
console.log(arr);

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!
Why not just do this?
var n = 123456789;
var digits = (""+n).split("");
What about:
const n = 123456;
Array.from(n.toString()).map(Number);
// [1, 2, 3, 4, 5, 6]
(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
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)
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]
const toIntArray = (n) => ([...n + ""].map(v => +v))
It is pretty short using Array destructuring and String templates:
const n = 12345678;
const digits = [...`${n}`];
console.log(digits);
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!
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('');
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;
}
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))
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]
const number = 1435;
number.toString().split('').map(el=>parseInt(el));
let input = 12345664
const output = []
while (input !== 0) {
const roundedInput = Math.floor(input / 10)
output.push(input - roundedInput * 10)
input = roundedInput
}
console.log(output)
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)
Move:
var k = Math.pow(10, i);
above
var j = k / 10;
var num = 123456789;
num = num.toString(); //'123456789'
var digits = num.split(""); //[ '1', '2', '3', '4', '5', '6', '7', '8', '9' ]
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))
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);
I ended up solving it as follows:
const n = 123456789;
let toIntArray = (n) => ([...n + ""].map(Number));
console.log(toIntArray(n));
Update with string interpolation in ES2015.
const num = 07734;
let numStringArr = `${num}`.split('').map(el => parseInt(el)); // [0, 7, 7, 3, 4]
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);
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.
const toIntArray = (n) => ([...n + ""].map(v => +v))

Categories

Resources