I have very long array containing numbers. I need to remove trailing zeros from that array.
if my array will look like this:
var arr = [1,2,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
I want to remove everything except [1, 2, 0, 1, 0, 1].
I have created function that is doing what is expected, but I'm wondering if there is a build in function I could use.
var arr = [1,2,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
for(i=arr.length-1;i>=0;i--)
{
if(arr[i]==0)
{
arr.pop();
} else {
break;
}
}
console.log(arr);
Can this be done better/faster?
Assuming:
var arr = [1,2,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
You can use this shorter code:
while(arr[arr.length-1] === 0){ // While the last element is a 0,
arr.pop(); // Remove that last element
}
Result:
arr == [1,2,0,1,0,1]
var arr = [1,2,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
var copy = arr.slice(0);
var len = Number(copy.reverse().join('')).toString().length;
arr.length = len;
arr -> [1, 2, 0, 1, 0, 1]
how it works
copy.reverse().join('') becomes "00000000000000000101021"
when you convert a numerical string to number all the preceding zeroes are kicked off
var len = Number(copy.reverse().join('')) becomes 101021
now by just counting the number i know from where i have to remove the trailing zeroes and the fastest way to delete traling elements is by resetting the length of the array.
arr.length = len;
DEMO
const arr = [0,0,0,1,2,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
My solution is:
arr.join('').replace(/0+$/g,'').split('').map(Number);
It will remove trailing zeros in the given array.
Result is [0,0,0,1,2,0,1,0,1];
If you also needed to remove leading zeros, you can adjust the regex like this:
arr.join('').replace(/^0+|0+$/g,'').split('').map(Number);
Now It will remove not only trailing zeros, but leading zeros too.
Result is [1,2,0,1,0,1];
Accepted answer is perfectly well. Just for fun here is a reducing approach.
var a = [1,0,1,0,1,0,1,2,3,4,5,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0];
f = a => { var b = true;
return a.reduceRight((r,n,i) => ( b ? n && ( b = false
, r[i] = n
)
: r[i] = n
, r
)
, []
);
};
console.log(f(a));
Here's a one-liner representing javascript at both its best and worst at the same time.
var arr = [1,2,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
arr.slice(0,arr.reduceRight(([d,l],c) => [d||c,l-!(d||c)], [false,arr.length])[1])
Output:
[ 1, 2, 0, 1, 0, 1 ]
A simpler immutable approach using reduceRight
const arr = [1,2,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
const prunedArray = arr.reduceRight((acc, item) => {
if(item === 0 && acc.length === 0) {
return acc;
}
return acc.concat(item);
}, []);
console.log(prunedArray); // [1, 0, 1, 0, 2, 1]
Related
I was wondering how I'd go about implementing a method in javascript that removes all elements of an array that clear a certain condition. (Preferably without using jQuery)
Ex.
ar = [ 1, 2, 3, 4 ];
ar.removeIf( function(item, idx) {
return item > 3;
});
The above would go through each item in the array and remove all those that return true for the condition (in the example, item > 3).
I'm just starting out in javascript and was wondering if anyone knew of a short efficient way to get this done.
--update--
It would also be great if the condition could work on object properties as well.
Ex.
ar = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ];
ar.removeIf( function(item, idx) {
return item.str == "c";
});
Where the item would be removed if item.str == "c"
--update2--
It would be nice if index conditions could work as well.
Ex.
ar = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ];
ar.removeIf( function(item, idx) {
return idx == 2;
});
You can use Array filter method.
The code would look like this:
ar = [1, 2, 3, 4];
ar = ar.filter(item => !(item > 3));
console.log(ar) // [1, 2, 3]
You could add your own method to Array that does something similar, if filter does not work for you.
Array.prototype.removeIf = function(callback) {
var i = 0;
while (i < this.length) {
if (callback(this[i], i)) {
this.splice(i, 1);
}
else {
++i;
}
}
};
To me, that's one of the coolest features of JavaScript. Ian pointed out a more efficient way to do the same thing. Considering that it's JavaScript, every bit helps:
Array.prototype.removeIf = function(callback) {
var i = this.length;
while (i--) {
if (callback(this[i], i)) {
this.splice(i, 1);
}
}
};
This avoids the need to even worry about the updating length or catching the next item, as you work your way left rather than right.
You can use Array.filter(), which does the opposite:
ar.filter(function(item, idx) {
return item <= 3;
});
You can use lodash.remove
var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) {
return n % 2 == 0;
});
console.log(array);
// => [1, 3]
console.log(evens);
// => [2, 4]
Make it a one-liner with arrow function:
ar = ar.filter(i => i > 3);
simply write the following example if condition could work on object properties as well
var ar = [ {num:1, str:"a"}, {num:2, str:"b"}, {num:3, str:"c"} ];
var newArray = [];
for (var i = 0, len = ar.length; i<len; i++) {
if (ar[i].str == "b")
{newArray.push(ar[i]);};
};
console.log(newArray);
See the example Live Example
if you need to remove exactly one item, and you know for sure that the item exists, you can use this one-liner:
ar.splice(ar.findIndex(el => el.id === ID_TO_REMOVE), 1);
// or with custom method:
let ar = [ {id:1, str:"a"}, {id:2, str:"b"}, {id:3, str:"c"}, {id:4,str:"d"} ];
ar.removeById = id => ar.splice(ar.findIndex(el => el.id === id), 1);
ar.removeById(ID_TO_REMOVE);
http://jsfiddle.net/oriadam/72kgprw5/
ES6 only
I love these kinds of questions and just a different version from me too... :)
Array.prototype.removeIf = function(expression) {
var res = [];
for(var idx=0; idx<this.length; idx++)
{
var currentItem = this[idx];
if(!expression(currentItem))
{
res.push(currentItem);
}
}
return res;
}
ar = [ 1, 2, 3, 4 ];
var result = ar.removeIf(expCallBack);
console.log(result);
function expCallBack(item)
{
return item > 3;
}
My solution for an array of numbers would be:
ar = ar.filter(item => item < 4);
For the in-place remove, my solution is
ar.filter(item => !(item > 3))
.forEach(obsoleteItem => ar.splice(ar.indexOf(obsoleteItem), 1));
Incorrect way
First of all, any answer that suggests to use filter does not actually remove the item. Here is a quick test:
var numbers = [1, 2, 2, 3];
numbers.filter(x => x === 2);
console.log(numbers.length);
In the above, the numbers array will stay intact (nothing will be removed). The filter method returns a new array with all the elements that satisfy the condition x === 2 but the original array is left intact.
Sure you can do this:
var numbers = [1, 2, 2, 3];
numbers = numbers.filter(x => x === 2);
console.log(numbers.length);
But that is simply assigning a new array to numbers.
Correct way to remove items from array
One of the correct ways, there are more than 1, is to do it as following. Please keep in mind, the example here intentionally has duplicated items so the removal of duplicates can be taken into consideration.
var numbers = [1, 2, 2, 3];
// Find all items you wish to remove
// If array has objects, then change condition to x.someProperty === someValue
var numbersToRemove = numbers.filter(x => x === 2);
// Now remove them
numbersToRemove.forEach(x => numbers.splice(numbers.findIndex(n => n === x), 1));
// Now check (this is obviously just to test)
console.log(numbers.length);
console.log(numbers);
Now you will notice length returns 2 indicating only numbers 1 and 3 are remaining in the array.
I have a sample array as
const arr=[0,2,4,6]
I want to check if they have a common difference in them, which is 2 and yes in above array.
There could be more efficient way to do this. I tried using a simple for loop as:
const arr = [0,2,4,6];
for(let i=0;i<arr.length-1;i++){
if(arr[i]+2==arr[i+1]){
console.log(true);
}
else{
console.log(false);
}
}
This could give me result as true,true,true and push all values to a new array then check if all are true and finally I would get true
It would be helpful if there is a more efficient way to do this; any help appreciated.
Assuming the array is sorted, you can do it pretty simply with .every().
const arr = [0,2,4,6];
const itvl = arr[1] - arr[0];
const result = arr.slice(0, -1).every((n, i) =>
itvl === arr[i + 1] - n
)
console.log(result);
This starts off by calculating the first interval, then it iterates the array (except the last index) using .every() to test that the next index minus the current one is equal to that pre-calculated index.
You can do this. It's better to stop as soon as you find a false rather than testing all the values.
const arr=[0,2,4,6]
var r = true
for (var i=1; i<arr.length-1 && r; i++) {
r = ((arr[i+1] - arr[i]) == (arr[i] - arr[i-1]))
}
console.log(r)
I assume what you mean by difference is the step value. For that, first find the difference between the first two elements ; then check whether the same difference holds for all consecutive values.
const arr = [0, 2, 4, 6];
let flag = true;
diff = arr[1] - arr[0];
for(let i = 1; i < arr.length-1; i++){
if(arr[i+1] - arr[i] != diff ){
flag = false;
break;
}
}
console.log(flag)
The code assumes the array size is atleast 2. Add an if guard if this is not always guaranteed.
Checks if numbers sum up to desired sum and if rest of numbers have same difference as desired in comments. (This should be a separate question.)
add up until s >= sum. return false if s isn't equal to set sum
if numbers left <= 2 return true
get difference of first 2 numbers
check difference of numbers, if not same difference return false
differences all same, return true
let arr = [0, 1, 3, 4, 6, 8, 10, 12];
const sum = 4
check = arr => {
let s = 0,
idx = arr.findIndex(x => (s+=x) >= sum ) + 1
if(s !== sum) return false
if(arr.length - idx < 3) return true
const diff = arr[idx+1] - arr[idx]
while(++idx<arr.length-1)
if(arr[idx+1] - arr[idx] !== diff) return false
return true
}
arr = [0, 1, 3, 4, 6, 8, 10, 12]
console.log(
check(arr)
)
arr = [0, 1, 3]
console.log(
check(arr)
)
arr = [0, 1, 3, 4, 6, 8, 10, 12, 11]
console.log(
check(arr)
)
I have implemented solution in javascript using two loops, below is the code
function getNums(arr){
var res = [];
var found = {};
var i, j;
var arrLen = arr.length;
for(i=0; i<arrLen; i++){
if(!found.hasOwnProperty(arr[i])){
for(j=0; j<arrLen; j++){
if(arr[i]+arr[j] === 0){
var num = arr[i];
if(num > 0){
res.push(num);
found[num] = 1;
}
}
}
}
}
return res;
}
console.log(getNums[-1, -2, 0, -4, 1, 4, 6]); // Output: [1, 4]
Whose time complexity is O(n2). Can someone suggest better solution / refined above to have less complexity?
You can just add the array to a Set and filter for inclusion in the set. Determining if something is in a set is constant time:
let arr = [-1, 2, 3, 1 , 3, -3, 4, -6]
let s = new Set(arr)
// all positive numbers with corresponding negatives in the set
let filtered = arr.filter(item => item > 0 && s.has(-1 * item))
console.log(filtered)
An alternative is to sort the array and then walk two pointers up the array as making matches along the way. The result will be sorted, however, which may not be the same order as the original array:
let arr = [-2, -3, 2, 5, 3, 1, -6, 2, -5]
arr.sort()
// get startig indexes
let i = 0, j = arr.findIndex(n => n > 0)
let res = []
if (j > -1) { // only if there are positive numbers in the array
while(arr[i] < 0 && j < arr.length){
if (-1 * arr[i] === arr[j]){
res.push(arr[j++])
} else if(-1 * arr[i] > arr[j]){
j++
} else if(-1 * arr[i] < arr[j]){
i++
}
}
}
console.log(res)
You could take a single loop approach by counting the values.
function getNums(array) {
var count = Object.create(null),
result = [];
array.forEach(v => {
if (count[-v]) {
result.push(Math.abs(v));
count[-v]--;
return;
}
count[v] = (count[v] || 0) + 1;
});
return result;
}
console.log(getNums([1, 2, -3, -4, 2, 3, 4, 4, -4]));
Before the downvotes... This answer is not the shortest javascript code, but the algorithm - I think it is what the original question was about.
One way to get rid of nested loops is to use more memory to store intermediate structures. In your case, you want to store not just the "found" flag, but negative, positive values as well, so that at every iteration you can set the found flag. Then you also use the "found" flag to prevent adding the results 2nd time.
var f = function(arr) {
let hash = {};
let res = [];
for (var i = 0; i < arr.length; i++) {
// put value into the hash map for future use
hash[arr[i]] = arr[i];
var absVal = Math.abs(arr[i]);
// if value is not 0 AND if it has not been found yet (x+value hash) AND if both negative and positive values are present
if( arr[i] !== 0 && !hash["x"+absVal] && (hash[arr[i]] + hash[-arr[i]] === 0)){
// then set the found hash to true
hash["x"+absVal] = true;
// and push to the resut
res.push(absVal);
}
}
// return the result
return res;
}
Another solution is to use filter and includes prototype functions which are well optimized.
const getNums = (arr) => arr.filter((num, index) => num > 0 && !arr.includes(num, index + 1) && arr.includes(-num));
I have an array with repeating values:
[0, 1, 6, 0, 1, 0]
What is an efficient way to return the highest amount that a specific value repeats?
In the example array I would want the script to return 3 because the number 0 repeats the most often and it repeats 3 times.
I'm already using jQuery and Underscore.
If you use lodash...
_.max(_.countBy(a,_.identity))
More about lodash: http://lodash.com/
This is similar to the basic approach, but utilizes underscore's reduce and max functions. If you had a really really really large array, I hope it's clear how you could parallelize this with a map phase before the reduce.
var arr = [1,0,2,3,4,0,3,0];
var counts = _.reduce(arr, function(counts, val) {
if (counts[val]) {
counts[val]++;
} else {
counts[val] = 1;
}
return counts;
}, {});
return _.max(counts);
Yay, this is like a google interview question lol. I would recommend looping through your array once and maintaining an associative array of each element as you encounter it in the while incrementing a counter.
For example:
http://jsfiddle.net/btKjX/
var a = [0, 0 , 2, 2, 3, 3, 3, 3];
var counts = {};
for(var i = 0, il = a.length; i < il; i++){
var num = a[i];
if(typeof counts[num] === 'undefined'){
counts[num] = 0;
}
counts[num]++;
}
var max = -1;
for(var c in counts){
if(counts[c] > max){
max = counts[c];
}
}
console.log(max);
a hacky way might be to sort it, split it on every value change and then look at the length of each string, but let's try something more reasonable:
var nums = [0, 1, 6, 0, 1, 0]
var occurence = {}
$.each(nums, function(a, num_id) {
if (occurence[num_id] != null) {
occurence[num_id]++;
} else {
occurence[num_id] = 1;
}
});
occurence would then have the number of occurences of every value in nums, with the number itself being the key.
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));