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,
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.