How to find the sum of an array of numbers

后端 未结 30 2628
醉话见心
醉话见心 2020-11-21 13:36

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,

30条回答
  •  悲哀的现实
    2020-11-21 14:11

    Accuracy

    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

提交回复
热议问题