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)
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);
Here is a ES6 version filter utility:
// Unique is only that item, if we find him in array on the same index.
const onlyUniqueProperty = prop => (value, index, self) =>
self.findIndex(item => item[prop] === value[prop]) === index;
// Usage:
const uniqueItems = items.filter(onlyUniqueProperty('key'));
If we want to support both JS and Immutable.js objects, small update:
const getProp = (obj, prop) => typeof obj.get === 'function' ? obj.get(prop) : obj[prop];
// Unique is only that item, if we find him in array on the same index.
const onlyUniqueProperty = prop => (value, index, self) =>
self.findIndex(item => getProp(item, prop) === getProp(value, prop)) === index;
// Usage:
const uniqueItems = items.filter(onlyUniqueProperty('key'));
var uniqueArray = []
for (var i = 0; i < array.length; i++) {
var uniquevalue = array[i];
unique[array.KEY] = uniquevalue;
}
for (var name in unique) {
var uniqueObject = unique[name];
uniqueArray.push(uniqueObject);
}