Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove all elements that occur more than once from array [duplicate]

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'];
like image 816
peter flanagan Avatar asked Dec 08 '22 13:12

peter flanagan


1 Answers

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

like image 71
Fabrizio Calderan Avatar answered Dec 10 '22 01:12

Fabrizio Calderan