c.reynolds c.reynolds - 17 days ago 7
Javascript Question

Remove all items that have duplicates in array Javascript

I have searched on here and have not found a solution. Obviously I will be corrected if I am wrong. What I am trying to do is return values that do not have a duplicates in an array.

Examples:

myArr = [2,1,2,3] // answer [1,3]


myArr = [3,1,2,2,3] // answer [1]


I would post some code but I have not been able to figure this out myself and the only code examples I have found are for removing any duplicate values.

The possible solution above is to return no duplicates... I am trying to return values that are don't have duplicates.

Answer

One option is to use the optional second argument to indexOf to find duplicate indexes. Consider that for a given element e and an index i:

  1. if e is the first of two identical elements in the array, indexOf(e) will return i and indexOf(e, i + 1) will return the index of the second element.
  2. if e is the second of two identical elements in the array, indexOf(e) will return the index of the first element, and indexOf(e, i + 1) will return -1
  3. if e is a unique element, indexOf(e) will return i and indexOf(e, i + 1) will return -1.

Therefore:

myArr.filter(function (e, i, a) {
  return a.indexOf(e) === i && a.indexOf(e, i + 1) === -1
});