This question already has an answer here:
I seem to only find ways to remove duplicates from an array using other JS libraries but I'm looking to do it in pure JS or typescript since I'm working on an Angular project.
My problem is that I may get an array that has duplicate entries, such as this one:
data [0: {Id: 1, Definition: "House"},
1: {Id: 1, Definition: "House"}]
And I want to filter it out so that I only get
data [0: {Id: 1, Definition: "House"}]
I've tried it using this method but I still get duplicate entries
let uniqueArray = data.filter(function(item, pos) {
return data.indexOf(item) == pos;
})
If the ID is what determines identity, then you could use a Map or a plain Object to dedupe. Same IDs will take the same spot on the map, so you end up with unique objects (if the above assumptions about IDs hold).
EDIT: In case that you want the same but you may have objects with the same ID but differing in other fields, a Map comes in handy because it can take whole objects as keys:
You can achieve what you want in this way:
You can check if the value is already there in your final array using 'some'
You can also achieve this by 'reduce' in clean and elegant way:
As suggested by @Ezequiel using
some
insideforEach
orreduce
making the time complexity of order of n square. For smaller sets of data usingreduce
andsome
is an elegant approach. But if you are dealing with arrays of very large length, you must avoid order of n square time complexity Here is one such approach withfilter
:You can use
Id
key of the object to get the unique object usingarray#reduce
in an object accumulator and get all the object of this object usingObject.values()
.