From 3a964f61f920385b5645f3772741a895503c978a Mon Sep 17 00:00:00 2001 From: Vasily Guzov Date: Thu, 3 Oct 2024 12:57:45 +0300 Subject: [PATCH] [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. --- lib/sumArray.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 lib/sumArray.ts diff --git a/lib/sumArray.ts b/lib/sumArray.ts new file mode 100644 index 0000000..a0b4b18 --- /dev/null +++ b/lib/sumArray.ts @@ -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))