How to find the sum of an array of numbers

后端 未结 30 2598
醉话见心
醉话见心 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:21

    Here's an elegant one-liner solution that uses stack algorithm, though one may take some time to understand the beauty of this implementation.

    const getSum = arr => (arr.length === 1) ? arr[0] : arr.pop() + getSum(arr);
    
    getSum([1, 2, 3, 4, 5]) //15
    

    Basically, the function accepts an array and checks whether the array contains exactly one item. If false, it pop the last item out of the stack and return the updated array.

    The beauty of this snippet is that the function includes arr[0] checking to prevent infinite looping. Once it reaches the last item, it returns the entire sum.

提交回复
热议问题