5

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]
Community
  • 1
  • 1
OneLazy
  • 499
  • 4
  • 16

4 Answers4

10

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
4

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)
Christian Zosel
  • 1,424
  • 1
  • 9
  • 16
0

You might also do as follows;

function removeDuplicates(a){
  return a.sort((a,b) => a - b)
          .reduce((p,c,i,a) => c === a[i-1] || c === a[i+1] ? p : p.concat(c),[]);
}

var arr = [5,3,2,7,6,6,9,2,4,6,0,8,1,3,8,8,3];
console.log(removeDuplicates(arr))
Redu
  • 25,060
  • 6
  • 56
  • 76
-1

$(function() {
  var array = [1, 2, 3, 4, 5, 6, 6 ,6 ]
  console.log(removeDuplicate(array, 6))
});

function removeDuplicate(original, val) {
   if(!val) return original

   
   var filtered = _.filter(original, function(num){ return num != val; });
   return filtered
}
<script src="http://underscorejs.org/underscore.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Gaurav joshi
  • 1,743
  • 1
  • 14
  • 28