What is the recommended way to filter Objects with Unique property in the array in JS?

后端 未结 4 730
醉梦人生
醉梦人生 2021-01-29 06:53

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

4条回答
  •  情话喂你
    2021-01-29 07:17

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

提交回复
热议问题