javascript 计算对象数组中的重复项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10541068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:12:44  来源:igfitidea点击:

Count duplicates within an Array of Objects

javascriptarraysobjectcountduplicates

提问by Ben

I have an array of objects as follows within my server side JS:

我的服务器端 JS 中有一个对象数组,如下所示:

[
    {
        "Company": "IBM"
    },
    {
        "Person": "ACORD LOMA"
    },
    {
        "Company": "IBM"
    },
    {
        "Company": "MSFT"
    },
    {
        "Place": "New York"
    }
]

I need to iterate through this structure, detect any duplicates and then create a count of a duplicate is found along side each value.

我需要遍历这个结构,检测任何重复项,然后在每个值旁边创建一个重复项的计数。

Both of the values must match to qualify as a duplicate e.g. "Company": "IBM" is not a match for "Company": "MSFT".

这两个值必须匹配才能成为重复项,例如“公司”:“IBM”与“公司”:“MSFT”不匹配。

I have the options of changing the inbound array of objects if needed. I would like the output to be an object, but am really struggling to get this to work.

如果需要,我可以选择更改入站对象数组。我希望输出是一个对象,但我真的很难让它工作。

EDIT: Here is the code I have so far where processArray is the array as listed above.

编辑:这是我到目前为止的代码,其中 processArray 是上面列出的数组。

var returnObj = {};

    for(var x=0; x < processArray.length; x++){

        //Check if we already have the array item as a key in the return obj
        returnObj[processArray[x]] = returnObj[processArray[x]] || processArray[x].toString();

        // Setup the count field
        returnObj[processArray[x]].count = returnObj[processArray[x]].count || 1;

        // Increment the count
        returnObj[processArray[x]].count = returnObj[processArray[x]].count + 1;

    }
    console.log('====================' + JSON.stringify(returnObj));

回答by georg

For example:

例如:

counter = {}

yourArray.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter[key] = (counter[key] || 0) + 1
})

Docs: Array.forEach, JSON.stringify.

文档:Array.forEachJSON.stringify

回答by gion_13

Object.prototype.equals = function(o){
    for(var key in o)
        if(o.hasOwnProperty(key) && this.hasOwnProperty(key))
            if(this[key] != o[key])
                return false;
    return true;
}
var array = [/*initial array*/],
    newArray = [],
    ok = true;
for(var i=0,l=array.length-1;i<l;i++)
    for(var j=i;j<l+1;j++)
    {
       if(!array[i].equals(array[j]))
           newArray.push(array[i]);
    }