const removeDuplicates = inputArray => {
const ids = [];
return inputArray.reduce((sum, element) => {
if(!ids.includes(element.toString()){
sum.push(element);
ids.push(element.toString());
}
return sum;
}, []);
};
This solution will remove all the objects that aren't the first object with a certain Id.
We fill an Array
with the ids, then we check if the ids already are filled in the current list.
The above solution can be potentially slow if there is a lot of elements since you need to check the list of ids which is O(n) for each iteration in the inputArray
which would put the algorithm at O(n^2)+O(n)
So instead, we can sort it first based on toString()
then we can just verify that the current id didn't match the last id we saw.
const removeDuplicates = inputArray => {
const sortedArray = inputArray.sort((a,b) => (a.toString() > b.toString() ? 1 : (a.toString() < b.toString() ? -1 : 0)));
let lastSeen = undefined;
return sortedArray.reduce((sum, element) => {
if(lastSeen !== element.toString()){
sum.push(element);
}
lastSeen = element.toString();
return sum;
}, []);
};
Now the algorithm is O(n log n) + O(n) assuming sort uses Merge Sort