Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

javascript - Count duplicates within an Array of Objects

I have an array of objects as follows within my server side 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".

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.

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));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For example:

counter = {}

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

Docs: Array.forEach, JSON.stringify.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...