I have an array of numbers e.g. [2, 4, 5] and must get the factorials in a new array. E.g. [2, 24, 120]
I am using .map as you can see to perform the function on each integer in the array however, this does not work? I assume something is wrong with the recursive function?
Thanks.
function getFactorials(nums) {
if(nums > 1){
factarr = nums.map(x => x * (nums - 1));
}
return factarr;
}
You could take a function for the factorial and map the values.
The function has a recusive style with a check for the value. if the value is zero, then the function exits with one. Otherwise it returnd the product of the actual value and the result of the call of the function with decremented value.
The check uses an implict casting of a falsy to a boolean value for the conditional (ternary) operator ?:.
const fact = n => n ? n * fact(n - 1) : 1;
var array = [2, 4, 5],
result = array.map(fact);
console.log(result);
Just create a function that calculates the factorial of a given number then just use it as the callback for the map function.
As the main part is the way to calculate the factoriel, here's two manners to do that task
Factoriel function iterative way :
const fact = n => {
let f = 1,
i = n;
for(; i > 1; i--) f *= i;
return f;
};
console.log(fact(4)); /** outpuut: 24 **/
Factoriel function recursive way :
const fact = n => n > 1 ? n * fact(n - 1) : n;
console.log(fact(4)); /** outpuut: 24 **/
And the final code :
const arr = [2, 4, 5],
fact = n => n > 1 ? n * fact(n - 1) : n,
factArr = arr.map(i => fact(i));
console.log(factArr); /** output: [2, 24, 120] **/
You are doing the recursion wrong, my approach would be to define the factorial calculator as a separate function:
function getFactorials(nums) {
function factorial(n){
return n === 0 ? 1 : n * factorial(n - 1);
}
return nums.map(x => factorial(x));
}
console.log(getFactorials([0, 1, 2, 3, 4, 5 ,6]));
You need to calculate each factorial in array, your current code is not doing that. Consider following example:
function factorial(num) {
if (num === 0 || num === 1) {
return 1;
} else {
return num * factorial(num - 1);
}
}
const facts = [2, 4, 5];
const factsArr = facts.map(num => factorial(num));
In you code you was just multiplying each member of array by array itself.
Instead of doing it recursively, I took the solution from #Amin Jafari which uses reduce(). This function is quicker than the recursive solution.
First we generate an array. We do so by using Array(n + 1). n is the factorial so e.g. for 6! our n would be 6. We get the indices with keys() but Array() by itself only returns a truly empty array and keys() only returns an iterator. So we spread it and put the result of that into a new array. Thus, we have e.g. [0,1,2,3,4,5,6] (for n + 1 with n = 6). We exclude the 0 with slice(1).
Afterwards we finally apply reduce. Reduce iterates over all elements, applies a function while keeping track of an accumulator. Our accumulator here is the current product. So what happens is that 1 * 2 gets calculated and the result saved in a, our accumulator. Then we multiply a with the next value, so 2 * 2* and this happens until we went through our whole self generated array.
This function based on reduce we can then use to transform each value in our original array with map().
const factorial = n => [...Array(n+1).keys()].slice(1).reduce((a,c) => a * c),
data = [2, 4, 5];
let res = data.map(v => factorial(v));
console.log(res);
I know that this post has a lot of answers already, but I might have something to add:
If you are planning to use the recursive function a lot to calculate factorials, let's say you need this in a browser game every .5 secs, you will notice that it is consuming a lot of resources, mainly your time 😉.
My proposition is:
calculate the factorials once
store them in the app state
look them up instead of calculating them
example code (based on Nina Scholz's anwer):
// create this earlier, put it in the application state
const state = {lookupFact: []}
const fact = n => n ? n * fact(n - 1) : 1;
// only calculate the factorials once
function lookupFact(par) {
if (state.lookupFact.length == 0) {
for (var i = 0; i <= 170; i++) {
state.lookupFact[i] = fact(i)
}
}
return state.lookupFact[par]
}
// use it like this later on
console.log(lookupFact(1), lookupFact(10), lookupFact(5))
As I said, you should use this only if you have to calculate factorials all the time.
var arr = [2,3,4,5,6,7]
arr.map((value, ind) => {
var facts = 1;
for (value ;value > 0 ;value--) {
facts = facts *value;
}
console.log(facts);
})
Related
Is it possible to merge the two arr.forEach() functions in my code together?
Here is my code:
function countTriplets(arr, r) {
let count = 0;
let freq = {};
let arrSum = [];
arr.forEach((num) => {
freq[num] ? freq[num]++ : freq[num] = 1;
})
arr.forEach((number) => {
let sum = freq[number/r] * freq[number * r];
if(!isNaN(sum)) {
arrSum.push(sum);
}
});
console.log("freq", freq);
console.log("arrSum", arrSum);
count = arrSum.reduce((a, b) => a + b);
return count;
}
If you are wondering what my code is about. It's to count the amount of triplets in an array such as [1, 5, 5, 25, 125]. It's for HackerRank challenge: https://www.hackerrank.com/challenges/count-triplets-1/problem.
The main challenge posted in this link is:
You are given an array and you need to find number of tripets of
indices (i, j, k) such that the elements at those indices are in
geometric progression for a given common ratio r and i < j < k
.
For example, arr = [1, 4, 16, 64] . If r = 4, we have [1, 4,
16] and [4, 16, 64].
I got my solution/inspiration from watching this: https://www.youtube.com/watch?v=tBFZMaWP0W8.
As mentioned in #Bergi's answer, you can't combine the two for loops.
But I believe you can eliminate this step:
count = arrSum.reduce((a, b) => a + b);
Here's a version of the algorithm in the question that eliminates the final arrSum.reduce and uses reduce in place of forEach.
function countTriplets(arr, r) {
const freq = arr.reduce((freq, num) => {
freq[num] = freq[num] ? freq[num] + 1 : 1;
return freq;
}, {});
console.log('freq', freq);
const count = arr.reduce((sum, number) => {
const triplets =
freq[number / r] && freq[number * r]
? freq[number / r] * freq[number * r]
: 0;
return sum + triplets;
}, 0);
return count;
}
const arr = [1, 5, 5, 25, 125];
const count = countTriplets(arr, 5);
console.log(`count:`, count);
There's also the case where r == 1. That's a faster calculation, as the triplet count for each number is just the combinations formula:
freq! freq * (freq-1) * (freq-2)
triplets = ---------------- = ----------------------------
3! * (freq-3)! 6
Where n! means factorial of n.
Is it possible to merge the two arr.forEach() functions in my code together?
No. The algorithm relies on all the counts being computed first and evaluated second.
Is it possible to optimize my solution by merging two loops?
No. You won't achieve a better time complexity by merging them, it's still a linear solution (which is as good as it gets).
If you want to improve your code, I'd suggest to
use a Map instead of an object, it's better suited for this purpose
don't use isNaN to determine whether a key exists in your map
deal with edge case r=1 correctly (as mentioned by #trincot in the comments)
deal with edge case arr=[] correctly (the reduce doesn't work without an initial value)
To further improve the speed of your code, do some benchmarking. Apart from switching to a Map, try changing the forEach call to a for … of or for(let i=0; i<….length; i++) loop, and don't keep the individual counts in a temporary arrSum array but just directly sum them (count += sum). Run the benchmarks with inputs of different sizes and different triplet distributions.
I need to create a function that take as parameter an array and a target. It should return an array of arrays where the sum of these numbers equals to the target
sumPairs(array, target) {
}
For example:
sumPairs([1, 2, 3, 4, 5], 7) // output : [[2, 5], [3, 4]]
I know I have to use map(), and probably reduce(), set(), or filter() maybe (I read their documentation in MDN but still cant find out). I tried some ways but I can't get it.
If you guys could help me to find out how to dynamically create arrays and push them into a new array..
I read there some solutions (Split array into arrays of matching values) but I hate to just use created functions without knowing what they really do or how they work.
Some very basic code for achieving it, Just run all over combinations and conditionally add the items you want.
function sumPairs(array, target) {
var res = [];
for(var i = 0; i < array.length; i++){
for(var j = 0; j < array.length; j++){
if(i!=j && array[i]+array[j]==target &&
res.filter((x)=> x[0] == array[j] && x[1] == array[i]).length == 0 )
res.push([array[i], array[j]]);
}
}
return res;
}
var result = sumPairs([1, 2, 3, 4, 5], 7);
console.log(result);
Option 2 - see this answer for more options (like using reduce)
function sumPairs(array, target) {
return array.flatMap(
(v, i) => array.slice(i+1).filter(w => (v!=w && v+w==target)).map(w=> [w,v])
);
}
var result = sumPairs([1, 2, 3, 4, 5], 7);
console.log(result);
"The exercise says that it sould be arrays of pairs that sum the
target value so I think only 2 items"
If you need a pair that matches a sum and you pick any number from the list, you are left with
the following equation to solve num + x = sum where we want to find x. E.g. if you picked 7 and the target sum is 10 then you know you are looking for a 3.
Therefore, we can first construct a counting map of the numbers available in our list linear (O(n)) time and then search for matches in linear time as well rather than brute forcing with a quadratic algorithm.
const nums = [1, 2, 3, 4, 5];
console.log(findSumPairs(nums, 7));
function findSumPairs(nums, sum) {
const countByNum = countGroupByNum(nums);
return nums.reduce((pairs, num) => {
countByNum[num]--;
const target = sum - num;
if (countByNum[target] > 0) {
countByNum[target]--;
pairs.push([num, target]);
} else {
countByNum[num]++;
}
return pairs;
}, []);
}
function countGroupByNum(nums) {
return nums.reduce((acc, n) => (acc[n] = (acc[n] || 0) + 1, acc), {});
}
Here's another implementation with more standard paradigms (e.g. no reduce):
const nums = [1, 2, 3, 4, 5];
console.log(findSumPairs(nums, 7));
function findSumPairs(nums, sum) {
const countByNum = countGroupByNum(nums);
const pairs = [];
for (const num of nums) {
const target = sum - num; //Calculate the target to make the sum
countByNum[num]--; //Make sure we dont pick the same num instance
if (countByNum[target] > 0) { //If we found the target
countByNum[target]--;
pairs.push([num, target]);
} else {
countByNum[target]++; //Didin't find a match, return the deducted num
}
}
return pairs;
}
function countGroupByNum(nums) {
const countByNum = {};
for (const num of nums) {
countByNum[num] = (countByNum[num] || 0) + 1;
}
return countByNum;
}
You can also sort your array and find all the pairs with given sum by using two pointer method. Place the first pointer to the start of the array and the second pointer to the end.
if the sum of the values at the two places is :
More than target: Decrement your second pointer by 1
Less than target: Increment your first pointer by 1
Equal to target: This is one possible answer, push them to your answer array and increment your first pointer by 1 and decrement your second pointer by 1.
This is more performant solution with complexity O(n*log(n))
I have an array that I created using Array(...) and Array.prototype.map, like this:
var array_name = Array(255).map(function(undef, i) {
return i + 1;
});
The values of this array are:
[1, 2, 3, ..., 253, 254, 255]
This is an array that won't get modified, so the first value of this array will always be 1 and the last value of this array will always be 255.
I already know the index of each value is {value} - 1, so 200 would be 199, 199 would be 198, so on and so forth.
Let's say I want 255's opposite value, which would be 0, I could get that using array_name[0], but what if I wanted 200's opposite value, how would I know what the opposite index of 199 is so I could get it's value?
Do:
opposite_index = arr.length - index - 1
For example:
a = [1,2,3,4,5,6,7,8,9,10]
index = 3
a[index]
4
It's opposite is 7 so:
opposite_index = a.length - index - 1
a[opposite_index]
7
With reverse as per #Maheer Ali suggestion:
a.reverse()[index]
7
Your Array(255).map() create undefined array value.So do with Array#from length object.And pass your value.get index of the value and match with reverse array you get opposite value
let check = (val) => {
var array_name = Array.from({length:255},(a,b)=>b+1);
var nor_ind = array_name.indexOf(val);
var re_in = array_name.reverse(array_name).indexOf(val)
return ({nor_val:val,nor_ind:nor_ind,opp_val:re_in})
}
console.log(check(254))
First of all the code you provided doesn't create array [1,2,3...255]. It will create it will 255 empty items first you need to fill().
var arr = Array(255).fill().map((a,i) => i+1);
//Create an array which will have revese items.
let revarr= arr.reverse()
console.log(revarr[0]) //255
console.log(revarr[254]) // 1
If you don't want to create a reverse arr. You can create a function
var arr = Array(255).fill().map((a,i) => i+1);
const opp = (arr,num) => arr[arr.length - num - 1];
console.log(opp(arr,0));
console.log(opp(arr,254));
First, you gotta understand that there is weird behavior concerning Array(n).map(f) (it won't create the array you're expecting), see this answer for explanation, second, do this to get the opposite values:
/* fill it first with .fill(), see the question I linked for more explanation */
var array = Array(255).fill(undefined).map(function(undef, i) {
return i + 1;
});
function opposite(array, n) {
return array[array.length - n];
}
console.log(opposite(array, 255));
console.log(opposite(array, 200));
console.log(opposite(array, 199));
console.log(opposite(array, 1));
Notice that length - n is used instead of length - n - 1, because we're dealing with values from 1 to n, not from 0 to n - 1.
Subtract the index from (length-1) -> max index of the array
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function findOpp(index, length) {
maxIndex = length - 1;
if (index <= maxIndex && index >= 0) {
return maxIndex - index;
} else {
return 'You have enter a wrong index';
}
}
console.log(findOpp(-1, 10));
console.log(findOpp(0, 10));
console.log(findOpp(1, 10));
console.log(findOpp(2, 10));
console.log(findOpp(4, 10));
console.log(findOpp(5, 10));
console.log(findOpp(6, 10));
console.log(findOpp(7, 10));
console.log(findOpp(8, 10));
console.log(findOpp(9, 10));
console.log(findOpp(10, 10));
Using Maheer Ali's suggestion I managed to get the desired result by reversing the array and using indexOf to get the index of that number:
var numbers = Array(255).map(function(v, i) {
return i + 1;
});
var opposite_brightness = numbers.reverse()[numbers.indexOf(brightness)];
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);
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));