Given an array [1, 2, 3, 4]
, how can I find the sum of its elements? (In this case, the sum would be 10
.)
I thought $.each might be useful,
Sort array and start sum form smallest numbers (snippet shows difference with nonsort)
[...arr].sort((a,b)=>a-b).reduce((a,c)=>a+c,0)
arr=[.6,9,.1,.1,.1,.1]
sum = arr.reduce((a,c)=>a+c,0)
sortSum = [...arr].sort((a,b)=>a-b).reduce((a,c)=>a+c,0)
console.log('sum: ',sum);
console.log('sortSum:',sortSum);
console.log('sum==sortSum :', sum==sortSum);
// we use .sort((a,b)=>a-b) instead .sort() because
// that second one treat elements like strings (so in wrong way)
// e.g [1,10,9,20,93].sort() --> [1, 10, 20, 9, 93]
For multidimensional array of numbers use arr.flat(Infinity)
arr= [ [ [1,2,3,4],[1,2,3,4],[1,2,3,4] ],
[ [1,2,3,4],[1,2,3,4],[1,2,3,4] ] ];
sum = arr.flat(Infinity).reduce((a,c)=> a+c,0);
console.log(sum); // 60