DeeTee DeeTee - 5 months ago 24
Javascript Question

Javascript find and count duplicate key values

I have a JSON array as follows:

var testJSON = [
{ "AssetA": "asset_a", "AssetB": "asset_b" },
{ "AssetA": "asset_a", "AssetB": "asset_b" },
{ "AssetA": "asset_c", "AssetB": "asset_d" },
{ "AssetA": "asset_c", "AssetB": "asset_e" }];

What I'd like to do is count all the duplicates. For example, I'd like my result to be another array, where the first two elements of the row are are the repeating values, and the third element is the number of times it repeats like so:

[{asset_a, asset_b,2},
{asset_c, asset_d,1},
{asset_c, asset_e,1}]

Here is what I have so far to be able to identify the duplicates, but it keeps getting hung up and my visual studio crashes:

for (var i = 0; i < testJSON.length; i++) {
for (var j = i + 1; j < testJSON.length;) {
if (testJSON[i][0] == testJSON[j][0] && testJSON[i][1] == testJSON[j][1])
// Found the same. Remove it.
console.log("they are equal");

// No match. Go ahead.

  1. testJSON[i][0]

I do not believe this will work like that. What you have is an ARRAY of OBJECTS.

Therefore, testJSON[i] will return an OBJECT, not an ARRAY, therefore testJSON[i][0] shouldn't return anything valuable. What you want is testJSON[i]['AssetA']

  1. Hangup

Another thing is when if (testJSON[i][0] == testJSON[j][0] && testJSON[i][1] == testJSON[j][1]) succeds on j = i+1. In this case, you will just keep iterating on the same value of j. You need to add j++ to your forloop and delete the else clause, or handle it otherwise for desired effect.

For example

for (var i = 0; i < testJSON.length; i++) {
    for (var j = i + 1; j < testJSON.length; j++) {
        if (testJSON[i]["AssetA"] == testJSON[j]["AssetA"] && 
            testJSON[i]["AssetB"] == testJSON[j]["AssetB"])
            console.log("they are equal");