Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering duplicate hashes from array of hashes - Javascript

I have an array of hashes, like this:

[{id: "4bf58dd8d48988d110941735", name: "italy"},
 {id: "4bf58dd8d48988d1c6941735", name: "skandi"},
 {id: "4bf58dd8d48988d147941735", name: "diner"},
 {id: "4bf58dd8d48988d110941735", name: "italy"},
 {id: "4bf58dd8d48988d1c4941735", name: "resto"},
 {id: "4bf58dd8d48988d14a941735", name: "vietnam"},
 {id: "4bf58dd8d48988d1ce941735", name: "fish"},
 {id: "4bf58dd8d48988d1c4941735", name: "resto"},
 {id: "4bf58dd8d48988d1c4941735", name: "resto"}]

I want to throw out duplicate hashes. Set doesn't work because hashes are unique objects.

I feel stuck and need a kick to think. Please advise!

like image 924
Dende Avatar asked Dec 21 '18 09:12

Dende


People also ask

How to remove duplicates from array in javaScript?

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 to prevent duplicate entry in javaScript?

To prevent adding duplicates to an array:Use the indexOf() method to check that the value is not present in the array. The indexOf method returns -1 if the value is not contained in the array. If the condition is met, push the value to the array.

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.


1 Answers

Try this

h.filter(( t={}, a=>!(t[a.id]=a.id in t) ))

Input array in h, time complexity O(n), explanation here.

let h = [{id: "4bf58dd8d48988d110941735", name: "italy"},
 {id: "4bf58dd8d48988d1c6941735", name: "skandi"},
 {id: "4bf58dd8d48988d147941735", name: "diner"},
 {id: "4bf58dd8d48988d110941735", name: "italy"},
 {id: "4bf58dd8d48988d1c4941735", name: "resto"},
 {id: "4bf58dd8d48988d14a941735", name: "vietnam"},
 {id: "4bf58dd8d48988d1ce941735", name: "fish"},
 {id: "4bf58dd8d48988d1c4941735", name: "resto"},
 {id: "4bf58dd8d48988d1c4941735", name: "resto"}]
 
 let t; // declare t to avoid use global (however works without it too)
 let r= h.filter(( t={}, a=>!(t[a.id]=a.id in t) ))

 
 console.log(JSON.stringify(r));
like image 92
Kamil Kiełczewski Avatar answered Sep 16 '22 16:09

Kamil Kiełczewski