Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get unique array with only filter in Javascript [duplicate]

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.

like image 813
GsMalhotra Avatar asked Nov 29 '16 04:11

GsMalhotra


People also ask

How do you duplicate an array in JavaScript?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.

How do you find duplicate numbers in an array if it contains multiple duplicates JavaScript?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.

How do you filter duplicates in an array?

Use the filter() method: The filter() method creates a new array of elements that pass the condition we provide. It will include only those elements for which true is returned. We can remove duplicate values from the array by simply adjusting our condition.

How do you remove duplicates from array of objects in JavaScript using filter?

To remove the duplicates from an array of objects: Create an empty array that will store the unique object IDs. Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.


2 Answers

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);
})
like image 113
Yaser Avatar answered Oct 18 '22 22:10

Yaser


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 });
like image 23
Ashutosh Jha Avatar answered Oct 18 '22 22:10

Ashutosh Jha