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.

Bhavesh Odedra
  • 10,990
  • 12
  • 33
  • 58
GsMalhotra
  • 1,837
  • 3
  • 14
  • 22

3 Answers3

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 });
John Slegers
  • 45,213
  • 22
  • 199
  • 169
Ashutosh Jha
  • 15,451
  • 11
  • 52
  • 85
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);
})
Yaser
  • 5,609
  • 1
  • 15
  • 27
0
var b = a.filter( function( item, index, inputArray ) {
       return inputArray.indexOf(item) == index;
});