Before people think this is the same as all these other answers on Stack Overflow regarding removing duplicates can you please look at what is returned as opposed to what I am looking to do.
I want to remove all elements that occur more than once. I have tried the following:
const a = ['Ronaldo', 'Pele', 'Maradona', 'Messi', 'Pele'];
const uniqueArray = a.filter(function(item, pos) {
return a.indexOf(item) == pos;
})
console.log(uniqueArray)
I want my uniqueArray
to be
['Ronaldo', 'Maradona', 'Messi'];
In short: keep the value if the position of the first occurrence of the element (indexOf
) is also the last position of the element in the array (lastIndexOf
).
If the indexes are not equal then the value is duplicated and you can discard it.
const a = ['Ronaldo', 'Pele', 'Maradona', 'Messi',
'Pele', 'Messi', 'Jair', 'Baggio', 'Messi',
'Seedorf'];
const uniqueArray = a.filter(function(item) {
return a.lastIndexOf(item) == a.indexOf(item);
});
console.log(uniqueArray);
/* output: ["Ronaldo", "Maradona", "Jair", "Baggio", "Seedorf"] */
Codepen Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With