Filtering duplicate hashes from array of hashes - Javascript
You can use reduce too
//I added comma to each object
const data= [{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"}]
const result= data.reduce((current,next)=>{
if(!current.some(a=> a.name === next.name)){
current.push(next);
}
return current;
},[])
console.log(result);
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));
Space for time
let arr = [
{ 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 map = {};
let rest = arr.filter((item) => {
if(map[item.id] === void 0) {
map[item.id] = item.id;
return true;
}
});
map = null;
console.log(rest);