Ask Your Question
3

In ES6, what is the method to produce an array containing distinct objects that are identified by their IDs?

asked 2021-09-15 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-12-31 07:00:00 +0000

pufferfish gravatar image

The method to produce an array containing distinct objects that are identified by their IDs in ES6 is by using the Set() constructor and the Array.from() method.

Firstly, create a Set containing unique IDs from the objects array.

const ids = new Set(objects.map(obj => obj.id));

Next, create a new array using the Array.from() method, filtering out objects whose IDs are already in the ids set.

const distinctObjects = Array.from(objects.filter(obj => !ids.has(obj.id)));

This will create a new array distinctObjects containing only the objects with distinct IDs.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-09-15 11:00:00 +0000

Seen: 12 times

Last updated: Dec 31 '21