I'm doing a coding challenge and I stumbled upon an issue that I think lies in the Math.min and Math.max methods. The goal of the function is to return the sum of an array after removing the min and max values (but only one of each e.g. [1,1,2,3,3] should only remove a single 1 and 3). Other rules are returning 0 for empty arrays, single value arrays, and null - this part seems to be working fine.
I ran some tests and I noticed my function was filtering multiple min and max values. For instance, my function returns 16 instead of 17 for sumArray([ 6, 2, 1, 1, 8, 10 ])
const sumArray = array => {
const minMax = num => {
return num !== Math.max(...array) && num !== Math.min(...array);
};
const reducer = (total, num) => {
return total + num;
};
// len check to prevent empty arrays after min/max removal
if (array === null || array.length <= 2) {
return 0
}
return array.filter(minMax).reduce(reducer);
}
console.log(sumArray([6, 2, 1, 1, 8, 10]));
I'm learning JS, so maybe I'm not even onto the real problem here. I just know the function works in all test cases except those that have multiple min or max values. Hoping to learn and improve from this, as it's my first time playing around with arrays. Thanks.
arr.sort().slice(1, -1).reduce(sum)... ? - Jonas Wilmssortsorts on string value, by default:1, 2, 11, 22, 33].sort()>[1, 11, 2, 22, 33]- Cerbrus