[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.
main
Vasily Guzov 1 year ago
parent f0bff99aa4
commit 3a964f61f9

@ -0,0 +1,13 @@
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))
Loading…
Cancel
Save