Variable min
will contain the sum of the 4 smallest items in a given array.
Variable max
will contain the sum of the 4 largest items in a given array.
JS:
function main() {
const arr = [1, 2, 3, 4, 5]
const min = arr.sort().filter((element, index, array) => element !== array[array.length - 1]).reduce((accumulator, currentValue) => {
return accumulator + currentValue
})
const max = arr.sort().filter((element, index, array) => element !== array[0]).reduce((accumulator, currentValue) => {
return accumulator + currentValue
})
console.log(min, max)
}
main()
As expected, [1,2,3,4,5]
will result in 10, 14. However, if the given array is [5,5,5,5,5]
, the program will return TypeError: Reduce of empty array with no initial value
.
Why is this?
Thanks.