Javad Sameri
Javad Sameri

Reputation: 1319

Sets of Object ecmascript 6 (es6)

I have an Array of Objects in this form :

[
{id : #mixed char and num , title : #string },
{id : #mixed char and num , title : #string } ...]

I wanted to iterate through it and remove the duplicated object, i used Set structure to do so , but the problem is that Sets add operator will accept the duplicated object I tried

let Unique = new Set([], X => x.id)

but wont help

Upvotes: 0

Views: 74

Answers (3)

Estus Flask
Estus Flask

Reputation: 223104

As the reference states,

The Set object lets you store unique values of any type, whether primitive values or object references.

If these are different object references, they won't be deduplicated. If objects need to be identified by id unique key, then Set is wrong choice. A map can serve this purpose:

new Map([
  [#mixed char and num, {id : #mixed char and num , title : #string }],
  ...
])

If objects don't contain anything but id and title, a map can be simplified to:

new Map([
  [#mixed char and num, #string],
  ...
])

Upvotes: 1

Koushik Chatterjee
Koushik Chatterjee

Reputation: 4175

you can use reduce with map of esmascript 6 and then pass the values to Set constructor. However you can use normal Object as well, Object.values in es6

new Set(arr.reduce((map,item)=>map.set(item.id, item), new Map()).values());

as you know you are identifing unique by id so just create a key with id pointing to the actual objects, hence the previous objects with the same id it will override and you will end up by having only one object against each id, then just get bthe values and construct your set.

Upvotes: 1

tymeJV
tymeJV

Reputation: 104795

You can remove all the duplicates with .filter

let uniqueArr = arr.filter((item, index) => {
    return arr.findIndex(item2 => item2.id === item.id) === index;
});

A fiddle demoing the concept: https://jsfiddle.net/4oanw972/

Upvotes: 1

Related Questions