按带有下划线的属性值过滤重复的集合对象(不区分大小写和修剪)

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

本文关键字:不区 对象 大小写 修剪 集合 下划线 属性 过滤      更新时间:2023-09-26

我正在寻找一种基于所选属性的值来过滤/拒绝集合中的对象的方法。具体来说,我需要过滤掉所选属性中包含重复值的对象。我需要将属性值转换为小写并修剪空白。

我已经有了删除重复项的方法,但我不知道如何包括小写转换和修剪。

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

如果集合是这样定义的

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

你应该使用_.uniq函数,像这样

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

根据签名,

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

第二个参数是判断集合是否已经排序。这很重要,因为如果对集合进行排序,就会有算法可以非常有效地找到唯一的数据。

第三个参数

应该是一个函数,它可以转换数据以获得要比较的键值。正如我们在示例中看到的,我们实际上从单个对象中选择name属性并将它们转换为小写字母。所以,这个小写的名字将代表这个对象,如果两个小写的名字是相同的,那么这些对象将被认为是彼此的副本。