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.
Asked: 2021-09-15 11:00:00 +0000
Seen: 12 times
Last updated: Dec 31 '21