From 2e48f32039c3428416f367d9bc73a1ac22d0f31f Mon Sep 17 00:00:00 2001 From: AdesounDeji Date: Mon, 8 Jan 2024 12:17:33 +0100 Subject: [PATCH] smallest two elemtnts TS --- .../FinfTheSmallestTwoElementsInAnArray.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 program/program/find-the-smallest-two-elements-in-an-array/FinfTheSmallestTwoElementsInAnArray.ts diff --git a/program/program/find-the-smallest-two-elements-in-an-array/FinfTheSmallestTwoElementsInAnArray.ts b/program/program/find-the-smallest-two-elements-in-an-array/FinfTheSmallestTwoElementsInAnArray.ts new file mode 100644 index 000000000..5e58aad4b --- /dev/null +++ b/program/program/find-the-smallest-two-elements-in-an-array/FinfTheSmallestTwoElementsInAnArray.ts @@ -0,0 +1,14 @@ +function findTheSmallestTwoElements(arr: number[]): number[] { + if (arr.length < 2) { + throw new Error("Array should have at least two elemnts.") + } + + const sortedArr = arr.slice().sort((a,b) => a - b); + return sortedArr.slice(0, 2); +} + +const numbers = [5, 2, 8, 1, 7, 3]; +const smallestTwo = findTheSmallestTwoElements(numbers); + +console.log("Original Array:", numbers); +console.log("Smallest Two Elements:", smallestTwo); \ No newline at end of file