计算对象数组中的重复项

Ben*_*Ben 6 javascript arrays object count duplicates

我在服务器端JS中有如下对象数组:

[
    {
        "Company": "IBM"
    },
    {
        "Person": "ACORD LOMA"
    },
    {
        "Company": "IBM"
    },
    {
        "Company": "MSFT"
    },
    {
        "Place": "New York"
    }
]
Run Code Online (Sandbox Code Playgroud)

我需要遍历这个结构,检测任何重复项,然后在每个值的旁边找到重复的计数.

这两个值必须匹配才能符合重复条件,例如"公司":"IBM"不匹配"公司":"MSFT".

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

编辑:这是我到目前为止的代码,其中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));
Run Code Online (Sandbox Code Playgroud)

geo*_*org 29

例如:

counter = {}

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

文档:Array.forEach,JSON.stringify.

  • 如果我想返回对象数组而不是对象怎么办? (2认同)