user2101317 user2101317 - 4 months ago 14
Javascript Question

Remove all repeated values in array and leave the ones that don't repeat in Javascript

Example: I have an array with repeated values 1 and 2


I want the result of that array to be an array of the values that dont repeat.



Without JQuery, you can use the filter method:

var nums = [1,1,2,2,3,4,5]
nums = nums.filter(function(val){
  return nums.indexOf(val)===nums.lastIndexOf(val);
// [3,4,5]

Otherwise, if in future you want to preserve repeated numbers, you can use:

for(var i=0; i<nums.length; i++) if(i!==nums.lastIndexOf(nums[i])) nums.splice(i, 1);
// [1,2,3,4,5]