Files
algorithms/lib/sumArray.ts
T
vaskes 3a964f61f9 [8kyu][array][fundamentals] sum array of numbers
https://www.codewars.com/kata/576b93db1129fcf2200001e6

Sum all the numbers of a given array ( cq. list ), except the highest
and the lowest element ( by value, not by index! ).The highest or lowest
element respectively is a single element at each edge, even if there are
more than one with the same value.Mind the input validation.
2024-10-03 12:57:45 +03:00

14 lines
438 B
TypeScript

export function sumArray(array: number[] | null): number {
if (Array.isArray(array) && array.length > 0) {
array.sort((a, b) => a - b);
array.shift();
array.pop();
return array.reduce((acc, currentValue) => acc + currentValue, 0)
}
return 0;
}
console.log(sumArray([6, 2, 1, 8, 10]), 16);
console.log(sumArray([6, 0, 1, 10, 10]), 17)
console.log('slice(1, -1): [ 6, 0, 1, 10, 10 ]', [6, 0, 1, 10, 10].slice(1, -1))