Recently, I came across a puzzling question for practice that left me intrigued by the two possible outcomes it could be seeking.
Naturally, I am eager to explore both solutions.
Consider an array given as:
let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];
I interpret the question as requiring the final result to be either of these two possibilities:
let finalResult = [1, 2, 3, 4, 5, 8, 9, 10];
OR:
let finalResult = [1, 9, 10];
The distinction lies in one solution removing all duplicate numbers while retaining the unique ones, and the other focusing on isolating the non-duplicate numbers.
Which leads me to the desire to craft two functions, each catering to one of the above scenarios.
An individual shared the following code snippet resulting in my second solution:
let elems = {},
arr2 = arr.filter(function (e) {
if (elems[e] === undefined) {
elems[e] = true;
return true;
}
return false;
});
console.log(arr2);
As for the function necessary for the first scenario (removing all duplicates), I find myself uncertain.