1

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

[1,1,2,2,3,4,5]

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

[3,4,5]
avatarZuko
  • 115
  • 5
  • 2
    Make an object whose properties are the values from the array, and values are the count of repetitions. After you're done, find all the keys with value = 1. – Barmar Oct 13 '16 at 19:22
  • @Barmar has the method I prefer to use-- quick and dirty, but it gets the job done efficiently. – Alexander Nied Oct 13 '16 at 19:24
  • @Bergi it's not a duplicate of that question. That will keep one copy of every value, he wants only the values that started with 1 copy. – Barmar Oct 13 '16 at 19:29
  • i'm trying to use filter function. `[1,1,2,2,3,4,5].filter(function(c,i,a){ return (a.indexOf(c) < i);` but Im not getting anywhere. – avatarZuko Oct 13 '16 at 19:36
  • @Barmar Ah, you're right. How about http://stackoverflow.com/questions/34498659/return-unique-element-that-does-not-have-duplicates-in-an-array then? – Bergi Oct 13 '16 at 19:39
  • is it always sorted? – Luke Kot-Zaniewski Oct 13 '16 at 19:40
  • @Bergi Yeah, that's the same, although for some reason the OP's function takes two arguments. – Barmar Oct 13 '16 at 19:43

2 Answers2

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

arr = arr.filter (function (value, index, array) {
    return array.indexOf (value) == array.lastIndexOf(value);
});

console.log(arr);

https://jsfiddle.net/qducmzqk/

Thalaivar
  • 23,282
  • 5
  • 60
  • 71
0

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]