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 in set may occur once; unique in set's collection.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -