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]

Answers:

Answer

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)

Answer

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);

Answer

$(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>

Answer

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))

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.