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
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'));