How to filter objects in array based on unique property here i have an array where KEY is the key value in the objects. How to filter the objects where key value is unique. Key
I would go with reduce()
, collecting unique elements into a Map
(it even preserves insertion order, if that is expected), and packing it back to an array at the end:
var array = [{
"KEY": "00001",
"ID": "1234",
"ID_DESC": "1234",
"NOT_UNIQUE_VALUE": "119.0",
"NOT_UNIQUE_TYPE": "this is not unique"
}, {
"KEY": "00001",
"ID": "1234",
"ID_DESC": "1234",
"NOT_UNIQUE_VALUE": "11019.0",
"NOT_UNIQUE_TYPE": "not unique type"
}, {
"KEY": "00002",
"ID": "2468",
"ID_DESC": "2468",
"NOT_UNIQUE_VALUE": "195.0",
"NOT_UNIQUE_TYPE": "not unique type",
}, {
"KEY": "00002",
"ID": "2468",
"ID_DESC": "2468",
"NOT_UNIQUE_VALUE": "195.0",
"NOT_UNIQUE_TYPE": "not unique type",
}]
var result = Array.from(array.reduce((m,o) => {
if(!m.has(o.KEY))
m.set(o.KEY, o);
return m;
}, new Map()).values());
console.log(result)