From 7fbdd383d81d32dca042dfde957da71775d24e31 Mon Sep 17 00:00:00 2001 From: Faizal Imam <88795778+Faizalimam990@users.noreply.github.com> Date: Mon, 21 Oct 2024 19:28:27 +0530 Subject: [PATCH] Create question6.js --- .../question6.js | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 JavaScript Programs Using Functions/question6.js diff --git a/JavaScript Programs Using Functions/question6.js b/JavaScript Programs Using Functions/question6.js new file mode 100644 index 0000000..49f2757 --- /dev/null +++ b/JavaScript Programs Using Functions/question6.js @@ -0,0 +1,22 @@ +// Question +// Write a function uniqueElements(arr) that takes an array of numbers as input and returns a new array containing only the unique elements from the input array. The order of the unique elements in the output array should match their first appearance in the input array. +// EXAMPLE +// console.log(uniqueElements([1, 2, 2, 3, 4, 4, 5])); // Output: [1, 2, 3, 4, 5] +// console.log(uniqueElements([5, 5, 5, 1, 2, 3, 3])); // Output: [5, 1, 2, 3] +// console.log(uniqueElements([])); // Output: [] + + +//ANSWER:- +function uniqueElements(arr) { + const uniqueArray = []; + const seen = new Set(); + + for (const element of arr) { + if (!seen.has(element)) { + seen.add(element); + uniqueArray.push(element); + } + } + + return uniqueArray; +}