Lodash:`_uniq()`的反义词是什么?

时间:2016-08-29 02:20:26

标签: lodash

lodash中的_.uniq()会从数组中删除重复项:

var tst = [
 { "topicId":1,"subTopicId":1,"topicName":"a","subTopicName1":"w" },
 { "topicId":2,"subTopicId":2,"topicName":"b","subTopicName2":"x" },
 { "topicId":3,"subTopicId":3,"topicName":"c","subTopicName3":"y" },
 { "topicId":1,"subTopicId":4,"topicName":"c","subTopicName4":"z" }]

var t = _.uniq(tst, 'topicName')

返回:

[ {"topicId":1,"subTopicId":1,"topicName":"a","subTopicName1":"w" }, 
  { topicId: 2, subTopicId: 2, topicName: 'b', subTopicName2: 'x' },
  { topicId: 3, subTopicId: 3, topicName: 'c', subTopicName3: 'y' } ]

与此相反的是什么?它应该只返回每个重复对象的单个对象:

[ { topicId: 3, subTopicId: 3, topicName: 'c', subTopicName3: 'y' } ]

1 个答案:

答案 0 :(得分:1)

我不认为这是一种内置的方法,这里有一些应该做的事情:

function dupesOnly(arr, field) {
    var seen = {},
        ret = [];

    arr.forEach(function(item) {
        var key = item[field],
            val = seen[key];

        if (!val) {
            seen[key] = val = {
                initial: item,
                count: 0
            }
        }

        if (val.count === 1) {
            ret.push(val.initial);
        }
        ++val.count;
    });

    return ret;
}