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]
7
  • 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. Commented Oct 13, 2016 at 19:22
  • @Barmar has the method I prefer to use-- quick and dirty, but it gets the job done efficiently. Commented Oct 13, 2016 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. Commented Oct 13, 2016 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. Commented Oct 13, 2016 at 19:36
  • @Barmar Ah, you're right. How about stackoverflow.com/questions/34498659/… then? Commented Oct 13, 2016 at 19:39

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

Comments

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]

1 Comment

thanks criz it worked!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.