9

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.

3

3 Answers 3

14

You can simply do it in JavaScript, with the help of the second - index - parameter of the filter method:

var a = [2,3,4,5,5,4];
a.filter(function(value, index){ return a.indexOf(value) == index });
Sign up to request clarification or add additional context in comments.

3 Comments

I will be happy if u explain this "function(d,i){return a.indexOf(d)==i}"
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
Thanks.You have given a simple,tricky and great answer to this problem
6

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

Comments

0
var b = a.filter( function( item, index, inputArray ) {
       return inputArray.indexOf(item) == index;
});

2 Comments

Please add some explanation to your code
Please Refer Yaser Adel Mehraban sloution

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.