If you want to get rid of duplicates by a given key without using lodash
library you can do the following:
For a given array [{a: 5, b: 7}, {a: 5, b: 99}, {a: 6, b: 1}, {a: 6, b: 0}]
the expected result can be [{a: 5, b: 99}, {a: 6, b: 0}]
(the last values are taken)
to implement this simply:
- Create an object having a key as a value of 'a' property:
const array = [{a: 5, b: 7}, {a: 5, b: 99}, {a: 6, b: 1}, {a: 6, b: 0}];
const unique = array.reduce((acc, value) => {
acc[value.a] = value;
return acc;
}, {});
The unique
object will be the following:
{"5":{"a":5,"b":99},"6":{"a":6,"b":0}}
- Take the values of this object using:
const result = Object.values(unique);
The result
value will be:
[{"a":5,"b":99},{"a":6,"b":0}]
If you want only the first item of a duplicate to be taken change the code to:
const array = [{a: 5, b: 7}, {a: 5, b: 99}, {a: 6, b: 1}, {a: 6, b: 0}];
const unique = array.reduce((acc, value) => {
acc[value.a] = acc[value.a] || value; // note the changes at this line
return acc;
}, {});
const result = Object.values(unique);
The output will be:
[{"a":5,"b":7},{"a":6,"b":1}]