javascript - Remove array items where object property is not unique -
i have array objects , need remove duplicates based on data-itemid
prop.
this code:
const listitemsunique = [] listitems.map(item => { if (listitemsunique.indexof(item.props['data-itemid']) === -1) { listitemsunique.push(item) } });
it returns same array before, doing wrong?
the easiest , cleanest way use temporary set store items have returned array, while you're mapping through it. so:
let tempset = new set(); const listitemsunique = listitems.filter(item => { if(!tempset.has(item.props['data-itemid'])) { tempset.add(item.props['data-itemid']); return item; } });
then mapping usual.
demo
let listitems = [ {name: "a", props: {"data-itemid": 1}}, {name: "b", props: {"data-itemid": 1}}, {name: "c", props: {"data-itemid": 2}}, {name: "d", props: {"data-itemid": 3}}, {name: "e", props: {"data-itemid": 3}}, ]; //mock data let tempset = new set(); const listitemsunique = listitems.filter(item => { if(!tempset.has(item.props['data-itemid'])) { tempset.add(item.props['data-itemid']); return item; } }) console.log(listitemsunique.map(item => item.name)); //items "b" , "e" skipped
by way, set
great when dealing with, or wanting achieve, unique collection of data. have read on mdn more info on set
.
here's snippet docs:
set
objects collections of values. can iterate through elements of set in insertion order. value inset
may occur once; unique inset
's collection.
Comments
Post a Comment