本文介绍了Lodash:`_uniq()`的反面是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这将返回:

[ {"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' } ]

推荐答案

我认为没有内置方法,以下是应该做的事情:

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

这篇关于Lodash:`_uniq()`的反面是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 07:42