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
You can iterate over the members and look at the KEY property. If it's not been seen before, add it to a list of seen keys and return true. If it has been seen before, return false. E.g.
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 seenKeys = Object.create(null);
var result = array.filter(function(obj) {
return seenKeys[obj.KEY]? false : seenKeys[obj.KEY] = true;
});
console.log(result)
As an arrow function:
var seenKeys = Object.create(null);
var result = array.filter(obj => seenKeys[obj.KEY]? false : seenKeys[obj.KEY] = true);