Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have an array:

var a = [2,3,4,5,5,4]

I want to get unique array out of given array like

b = [2,3,4,5]

I have tried

a.filter(function(d){return b.indexOf(d)>-1})

and I don't want to use for loop.

share|improve this question
    
    
Here are multiple examples - jstips.co/en/deduplicate-an-array with newer ES syntax, and future implementations (using Array Sets) – ioneyed 9 hours ago
    
use lodash library ( lodash.com/docs/#uniq) – Pratap 9 hours ago
up vote 6 down vote accepted

you can simply do it in java script , with the help of filter second parameter which is for indexing like this

var a = [2,3,4,5,5,4]
a.filter(function(d,i){return a.indexOf(d)==i})
share|improve this answer
    
I will be happy if u explain this "function(d,i){return a.indexOf(d)==i}" – Mohammad Sadiqur Rahman 9 hours ago
1  
i in parameter is for indexing , means when you check for second last 5 , index would be 4 but indexOf would be 3 so they dont match hence it wiill filter out – Ashu 8 hours ago
    
Thanks.You have given a simple,tricky and great answer to this problem – Mohammad Sadiqur Rahman 8 hours ago

This is not an Angular related problem. It can be resolved in a couple of ways depending which libraries you are using.

If you are using jquery:

var uniqeElements = $.unique([2,3,4,5,5,4]);

The output would be:

[2,3,4,5]

If you are using underscore:

var uniqeElements = _.uniq([2,3,4,5,5,4]);

Same output.

And pure JS code:

var unique = [2,3,4,5,5,4].filter(function(elem, index, self) {
    return index == self.indexOf(elem);
})
share|improve this answer
var b = a.filter( function( item, index, inputArray ) {
       return inputArray.indexOf(item) == index;
});
share|improve this answer
1  
Please add some explanation to your code – Yury Fedorov 6 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.