function sumArray(array) {
array.sort(function(a,b){return a-b})
console.log(array) //log1
array.splice(0, 1)
array.splice(-1, 1)
array.reduce(function(a,b){return a+b}, 0);
console.log(array) //log2
}
The log results are:
log 1: [ 1, 2, 6, 8, 10 ]
log 2: [ 2, 6, 8 ] instead of 16.
Because, reduce
method does not mutate the array
. reduce returning new value which you are not using to console.log
function sumArray(array) {
array.sort(function(a,b){return a-b})
console.log(array) //log1
array.splice(0, 1)
array.splice(-1, 1)
const sum = array.reduce(function(a,b){return a+b}, 0);
console.log(sum) //log2
return sum;
}
console.log('Sum: ', sumArray([2, 5, 6]));
Also, for use case of calculating sum, you dont need to pass 0
for init value. reduce
consider the first value as init value and continue from 2nd item from array. MDN reduce
const sum = array.reduce((a, b) => a + b);