Lodash: What's the opposite of `_uniq()`?

允我心安 提交于 2020-01-05 04:25:11

问题


The _.uniq() in lodash removes duplicates from an array:

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')

This returns:

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

What's the opposite of this? It should only return a single object for each duplicate object:

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

回答1:


I don't think there's a built in method, here's something that should do the job:

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;
}


来源:https://stackoverflow.com/questions/39197701/lodash-whats-the-opposite-of-uniq

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