简体   繁体   中英

Problem with JS Math methods: function is removing multiple min/max values (I think?)

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 eg [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.

Your minMax filter is filtering out all occurrences of the highest or lowest values.

All values that match the lowest or highest value are removed there. That's not a bug in min or max , but in how you use the returned value.

I'd suggest reworking your function:

  1. Find the min / max, and store those in variables.
  2. Add up everything in the array, store that in a variable.
  3. Subtract the min and max from the total.

I really wouldn't botter to do any of the filtering, just remove once the min value and once the maximum value after you summed the array :)

 const sumArray = 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 } const min = Math.min( ...array ); const max = Math.max( ...array ); return array.reduce(reducer) - min - max; } console.log(sumArray([6, 2, 1, 1, 8, 10])); 

Your original code doesn't work (and is actually "expensive" because you recalculate the minimum and maximum on every iteration), because you will remove all minimum values and all maximum values, and not only once, as you explained the rules were.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM