Home > katas > Sum without highest and lowest number with JavaScript (8kyu) [JavaScript]

Sum without highest and lowest number with JavaScript (8kyu) [JavaScript]


Chek kata on Codewars

Description:

Sum all the numbers of the array (in F# and Haskell you get a list) except the highest and the lowest element (the value, not the index!).
(The highest/lowest element is respectively 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.
Note:In C++ instead null an empty vector is used. In C there is no null.

Solution 1

function sumArray(array)  {
    if(array && array.length > 1) {
        const sortedArray = array.sort((a,b) => a - b).slice(1, -1)
        return sortedArray.reduce((acc, cur) => acc + cur, 0)
    }

    return 0
}

Solution 2

const sumNums = (acc, cur) => acc + cur

function sumArray(array) {
    return Array.isArray(array) && array.length > 1
            ? array.reduce(sumNums, 0) - Math.min(...array) - Math.max(...array)
            : 0
}
© 2020, Andrew Losseff