[removed] Remove duplicates of objects sharing same property value

后端 未结 12 1478
执念已碎
执念已碎 2020-11-30 06:00

I have an array of objects that I would like to trim down based on a specific key:value pair. I want to create an array that includes only one object per this s

12条回答
  •  一向
    一向 (楼主)
    2020-11-30 06:25

    This function removes duplicate values from an array by returning a new one.

    function removeDuplicatesBy(keyFn, array) {
        var mySet = new Set();
        return array.filter(function(x) {
            var key = keyFn(x), isNew = !mySet.has(key);
            if (isNew) mySet.add(key);
            return isNew;
        });
    }
    
    var values = [{color: "red"}, {color: "blue"}, {color: "red", number: 2}];
    var withoutDuplicates = removeDuplicatesBy(x => x.color, values);
    console.log(withoutDuplicates); // [{"color": "red"}, {"color": "blue"}]

    So you could use it like

    var arr = removeDuplicatesBy(x => x.custom.price, yourArrayWithDuplicates);
    

提交回复
热议问题