Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: remove duplicate values in array, including the original

Does anyone know how to remove duplicates in an array including the original value? I came across different snippets like this and this and some others but none in particular is removing the original node at the same time. Care to share a little snippet ? TIA!

Example:

[1, 1, 2, 3, 5, 5] -> [2, 3]
like image 880
OneLazy Avatar asked Dec 24 '22 23:12

OneLazy


2 Answers

You could use a check for index and last index.

var arr = [1, 1, 2, 3, 5, 5],
   res = arr.filter((a, _, aa) => aa.indexOf(a) === aa.lastIndexOf(a));

console.log(res);
like image 90
Nina Scholz Avatar answered Mar 09 '23 00:03

Nina Scholz


You could try filtering your array based on the number of occurrences of a specific value in that array:

var arr = [1, 1, 2, 3, 5, 5]

var res = arr.filter((el, _, arr) => {
      return arr.filter(el2 => el2 === el).length === 1
})

console.log(res)
like image 25
Christian Zosel Avatar answered Mar 09 '23 00:03

Christian Zosel