I'm currently working on a challenging kata in codewars, but I'm encountering some difficulties. My goal is to calculate the sum of all elements in an array except for the highest and lowest values.
This is my current implementation:
function sumArray(array) {
let largestVal = Math.max(array);
let lowestVal = Math.min(array);
let total = 0;
let arrLength = array.length;
console.log(`The lowest number is: ${lowestVal}`);
console.log(`Array is: ${array}`);
console.log(`Total is: ${total}`);
console.log(`The larget number is: ${largestVal}`);
return // [QUESTION] <= having problems in how to return the sum of each element except the largest and lowest values.
}
Your help is much appreciated!
EDIT-1: Updated code with @WLatif implementation
function validate(array) {
if (typeof array === 'object' && array instanceof Array && array.length > 1) {
return 1;
} else {
return 0;
}
}
function sumArray(array) {
if (validate(array)) {
let sorted = array.sort(function (a, b) { return a - b });
let largestVal = sorted.slice(-1).pop();
let lowestVal = sorted[0];
let total = array.reduce( function(prev, curr) { return prev + curr; }, 0 );
let arrLength = array.length;
console.log(`The lowest number is: ${lowestVal}`);
console.log(`Array is: ${array}`);
console.log(`Total is: ${total}`);
console.log(`The larget number is: ${largestVal}`);
return (total- lowestVal - largestVal);
} else {
console.log(`Not a valid array`);
}
}
The error message I'm receiving is:
Not a valid array ✘ Expected: 0, instead got: undefined
What am I missing?
Here are the instructions:
Sum all the numbers of the array except the highest and the lowest element (the value, not the index!).
(Only one element at each edge, even if there are more than one with the same value!)
Example:
{ 6, 2, 1, 8, 10 } => 16
{ 1, 1, 11, 2, 3 } => 6
If array is empty, null or None, or if only 1 Element exists, return 0.