Search code examples
javascriptarraysdebuggingmatharrow-functions

Sum without highest and lowest number


I've been spending a few hours trying to understand where the error is in this code. Debugging indicated that the output is 0 as it should be for any number less than 0. However, this code is still unable to pass the test:

function sumArray(array) 
{
  return array < 1 || array == null ? 0
    :array.reduce((a, b) => a + b) - Math.max(...array) - Math.min(...array);
  
  }

console.log(sumArray([-3]))

Solution

  • Definitely better:

    function sumArray(array) {
      
      if (array == null || array.length <= 1) {
        return 0
      }
      
      var max = Math.max(...array);
      var min = Math.min(...array);
      var sum = 0
      
      for (i = 0; i < array.length; i++) {
        sum += array[i];
       }
    
      return sum - max - min
    }