The easiest and cleanest way would be to use a temporary set to store which items you have previously returned to your array, while you're mapping through it. Like 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 do your mapping as 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" and "E" are skipped
By the way, Set
is great for when dealing with, or wanting to achieve, a unique collection of data. Have a read on the MDN for more info on Set
.
Here's a snippet from the docs:
Set
objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set
may only occur once; it is unique in the Set
's collection.