Here are some key points to consider:
- The
sum
function must have an initial value, typically set as 0
- Making a
return
statement inside the loop restricts it to just one iteration; move it outside the loop for multiple iterations.
- To avoid missing out on the last value in the array, ensure your loop iterates until
i < array.length - 1
- Instead of using the
sort
method with a time complexity of O(nlogn), opt for O(n) by utilizing Math.min
and Math.max
:
function sumArray(array) {
return array.length < 2 ? 0
: array.reduce((a, b) => a + b) - Math.min(...array) - Math.max(...array);
}
console.log(
sumArray([6, 2, 1, 8, 10])
)
Note: The code is written in ES6, compatible with major browsers except for Internet Explorer.
For older browser support:
function sumArray(array) {
return array.length < 2 ? 0
: array.reduce(function (a, b) {
return a + b;
}) - Math.min.apply(null, array) - Math.max.apply(null, array);
}
console.log(
sumArray([])
)
When dealing with very large arrays, consider using reduce
to fetch minimum and maximum values due to limitations on the number of arguments passed to a function call.