When looking to remove duplicates from an array, I'm never sure whether it's best to use built in Javascript features such as Set
to remove the duplicates then iterate through that to push the values into an array
OR
if it's best to iterate through the array and keep track of seen integers in a hashtable and splice out the duplicate if it's already been seen.
I've used both ways before but as far as efficiency goes, I'm not sure what is best.
For method 2 ( iterating and using hashtable), I assume the runtime for the loop is (On) since it's linear, but does the splice each time to remove the duplicate from the array add to that?
As far as Set efficiency goes, I really don't know what that is doing behind the scenes so I have no idea. However, the 2nd part of that would require a loop (On runtime) to put them into an array after they are in the Set.
method 1:
let array = [1,1,2,2,3,3];
let set = new Set([...array]);
let newArray = [];
set.forEach((num) => {
newArray.push(num);
})
method 2:
let array = [1,1,2,2,3,3];
let obj = {};
for (var x = array.length - 1; x >= 0; x--) {
if (obj[array[x]]) {
array.splice(x,1);
} else {
obj[array[x]] = 1;
}
}
EDIT: I know how to do this has been asked many times but I'm sort of asking for which method delivers the best runtime. Since splice takes O(n) each time, I am wondering how that scales vs. for example, using Set or another method.