[removed] Remove duplicates of objects sharing same property value

后端 未结 12 1470
执念已碎
执念已碎 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:19

    Try the following function:

    function trim(items){
        const ids = [];
        return items.filter(item => ids.includes(item.id) ? false : ids.push(item.id));
    }
    
    0 讨论(0)
  • 2020-11-30 06:20

    This is just another 'feature' based on yvesmancera's solution (after I started tinkering for my own solution) Also noted we are only allowed to currently use IE 11, so limited ES5 is allowed.

    var newArray = RemoveDuplicates(myArray,'Role', 2);
    
    function RemoveDuplicates(array, objKey, rtnType) {
    var list = [], values = [], value;
    for (var i = 0; i < array.length; i++) {
        value = array[i][objKey];
        if(values.indexOf(value) === -1){
            list.push(array[i]);
            values.push(value);
            }
        }
        if(rtnType == 1)
            return list;
        return values;
    };
    

    Hoping this will work for most, if not all arrays when filtering out objects based on a single object property value.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-30 06:25

    Here is the typescript way

        public removeDuplicates(originalArray:any[], prop) {
        let newArray = [];
        let lookupObject = {};
    
        originalArray.forEach((item, index) => {
            lookupObject[originalArray[index][prop]] = originalArray[index];
        });
    
        Object.keys(lookupObject).forEach(element => {
            newArray.push(lookupObject[element]);
        });
        return newArray;
    }
    

    And

    let output = this.removeDuplicates(yourArray,'color');
    
    0 讨论(0)
  • 2020-11-30 06:27

    Use Array.filter(), keeping track of values by using an Object as a hash, and filtering out any items whose value is already contained in the hash.

    function trim(arr, key) {
        var values = {};
        return arr.filter(function(item){
            var val = item[key];
            var exists = values[val];
            values[val] = true;
            return !exists;
        });
    }
    
    0 讨论(0)
  • 2020-11-30 06:32

    Off the top of my head there is no one function that will do this for you as you are dealing with an array of objects and also there is no rule for which duplicate would be removed as duplicate.

    In your example you remove the one with size: small but if you were to implement this using a loop you'd most likely include the first and exclude the last as you loop through your array.

    It may very well be worth taking a look at a library such as lodash and creating a function that uses a combination of it's API methods to get the desired behaviour you want.

    Here is a possible solution you could use making use of basic Arrays and a filter expression to check whether a new item would be considered a duplicate before being attached to a return result.

    var arrayWithDuplicates = [
        {"color":"red", "size": "small"},
        {"color":"green", "size": "small"},
        {"color":"blue", "size": "medium"},
        {"color":"red", "size": "large"}
    ];
    
    var reduce = function(arr, prop) {
      var result = [],
          filterVal,
          filters,
          filterByVal = function(n) {
              if (n[prop] === filterVal) return true;
          };
      for (var i = 0; i < arr.length; i++) {
          filterVal = arr[i][prop];
          filters   = result.filter(filterByVal);
          if (filters.length === 0) result.push(arr[i]);
      }
      return result;
    };
    
    console.info(reduce(arrayWithDuplicates, 'color'));
    

    You can check out some literature on Array filtering here If you need to provide a preference on which item to remove you could define extra parameters and logic that will make extra property checks before adding to a return value.

    Hope that helps!

    0 讨论(0)
提交回复
热议问题