Filter duplicate collection objects (case-insenstive and trim) by property value with underscore

时间秒杀一切 提交于 2019-12-24 12:05:51

问题


I'm looking for a way to filter / reject objects in a collection based on the value of a chosen property. Specifically I need to filter out objects that contain duplicate values for that chosen property. I need to convert the property value to lower case and trim the whitespace.

I already have my method for removing the duplicates but I can't figure out how to include the lowercase conversion and the trim.

removeDuplicates: function (coll, attr) {
      var uniques = _.map(_.groupBy(coll, function (obj) {
        return obj[attr];
      }), function (grouped) {
        return grouped[0];
      });

      return uniques;
    }

Any help would be appreciated.


回答1:


If the collection is defined like this

var array = [{
    name: "thefourtheye"
}, {
    name: "theFOURtheye"
}, {
    name: "thethirdeye"
}];

You should be using _.uniq function, like this

var attr = "name";
console.log(_.unique(array, false, function(currenObject) {
    return currenObject[attr].toLowerCase();
}));
# [ { name: 'thefourtheye' }, { name: 'thethirdeye' } ]

As per the signature,

uniq_.uniq(array, [isSorted], [iterator])

the second parameter is tell if the collection is already sorted. This is important, because if the collection is sorted, there are algorithms which can find the unique data very efficiently.

the third parameter, should be a function, which can transform the data to get the key value to compare. As we see in the example, we actually pick the name property from the individual objects and convert them to lower case letters. So, this lower cased name will represent this object and if two lowercased names are the same, then those objects will be considered as the duplicate of each other.



来源:https://stackoverflow.com/questions/22687038/filter-duplicate-collection-objects-case-insenstive-and-trim-by-property-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!