JavaScript - copy duplicates in an array of objects

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

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

I need to iterate over this structure, detect any duplicates, and then create a duplicate count next to each value.

Both values ​​must match to qualify as a duplicate, for example. Company: IBM is not suitable for Company: MSFT.

I have options for changing the incoming array of objects, if necessary. I would like the result to be an object, but I'm really trying to get it to work.

EDIT: Here is the code that I still have, where processArray is an array, as stated above.

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));
+5
source share
2

:

counter = {}

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

: Array.forEach, JSON.stringify.

+22
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]);
    }
+1

All Articles