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!
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.
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With