Why this array.reduce function is not reducing at all? Beginner

Viewed 529

I'm beginner to programming/stackoverflow and trying to create a function that sum elements of an array, without the lowest and highest elements.
So I decided to sort the array using ascending order and splice it to remove first and last values. Figured out that this was going to be the easiest way.
But now I have spent literally hours trying to debug it, watched several youtube videos and tried every array.reduce variant I could imagine and find on the internet, trying to under-****ing-stand array.reduce function and why it is not returning reduced array.
Could someone help me? By the way, if someone knows any ways to splice two values from an array without using array.splice two times, I would love to know. Thank you so much.

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.

3 Answers

You are logging the array, not the result of reduce. Assign the result of reduce to a variable and log it, just change the last 2 lines of your function to:

const sum = array.reduce(function(a,b){return a+b}, 0);
console.log(sum) //log2

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);

The reduce() works by returning the reduced value;

The reason you are still getting the array is that you are printing the array itself. You never got the reduced value into the variable.

Try using another variable instead of mutating the array variable.

function sumArray(array) {

  array.sort(function(a,b){return a-b})
  console.log(array) //log1
  
  array.splice(0, 1)
  array.splice(-1, 1)
  
  let ans = array.reduce(function(a,b){return a+b}, 0);
  console.log(ans) //log2
}

Related