'Return only unique objects from an array in Javascript
Having the following array:
const arr = [{ id: 'A', version: 0, name: 'first' },
{ id: 'A', version: 1, name: 'first' },
{ id: 'B', version: 0, name: 'second' },
{ id: 'A', version: 2, name: 'first' },
{ id: 'B', version: 1, name: 'second' }];
I need to use this as input for two drop-downs.
For the first drop-down it should show in the list only two values, A and B.
For doing that:
const firstDropdownOptions = [...new Set(arr.map((el) => el.id))];
Unfortunately, this returns ['A', 'B'] which doesn't contain any information about the other properties.
It would be more useful to be like:
[{ id: 'A', version: '0', name: 'first' }, { id: 'B', version: '0', name: 'second' }]
Any ideas on how to make it return the above array?
Solution 1:[1]
I have found a short solution to this problem:
const result = arr.filter((value, index, self) => {
return self.findIndex(v => v.id === value.id) === index
});
Solution 2:[2]
Observation : As you are only returning id in array.map() method. Hence, it is giving you only unique Id's [A, B] in a new array. To get all the other properties you have to fetch via condition to check if version === 0.
Working Demo :
const arr = [{ id: 'A', version: 0, name: 'first' },
{ id: 'A', version: 1, name: 'first' },
{ id: 'B', version: 0, name: 'second' },
{ id: 'A', version: 2, name: 'first' },
{ id: 'B', version: 1, name: 'second' }];
const firstDropdownData = arr.filter((obj) => obj.version === 0);
console.log(firstDropdownData);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Leo Messi |
| Solution 2 | Rohìt JÃndal |
