Counting duplicate JSON array values using hashmap with javascript

Viewed 322

I'm having trouble wrapping my mind around javascript hashmaps and JSON arrays. I'm trying to count duplicate import countries from a JSON array. For instance the data is:

[
  {
    "id": 1,
    "import_country": "Russia",
    "model": "Express 2500",
    "make": "Chevrolet",
    "sold_by": "Sibylla Kneale",
    "sale_price": 14702
  },
  {
    "id": 2,
    "import_country": "Philippines",
    "model": "G-Class",
    "make": "Mercedes-Benz",
    "sold_by": "Gabie Gradwell",
    "sale_price": 19142
  },
  {
    "id": 3,
    "import_country": "Russia",
    "model": "M",
    "make": "Infiniti",
    "sold_by": "Burl Pitkeathley",
    "sale_price": 18395
  }
]

This is what I have for code so far:

var country = [];
var temp = [];
const model = [];

const count = 0;
const response = await fetch('some api url where data is retrieved')
    .then(response => response.json())
    .then(data => {
        var key = {};
        for(i = 0; i< data.length; i++){
            if(temp.indexOf(data[i].import_country) == -1){
                temp.push(data[i][import_country]);
                var _data = {};

            }
        }
    });

My end goal is to have the total country count displayed on a graph.

2 Answers

A good way to do this would be to use a hashmap instead of arrays like you said.

If we update your code to be this:

var hashmap = {};

const response = await fetch('some api url where data is retrieved')
  .then(response => response.json())
  .then(data => {
    var key = {};
    for(i = 0; i< data.length; i++){
      let country = data[i]['import_country']; 
      if (hashmap[country] == void(0)) { // if it doesn't exist in the hashmap
        hashmap[country] = []; // create it in the map
      }
      hashmap[country].push(data[i]); // add it to the country array in the temp
    }
  }) 

If the data you are receiving above is correct, the output would look something like this:

{
  "Russia": [
    {"id":1,"import_country":"Russia","model":"Express 2500","make":"Chevrolet","sold_by":"Sibylla Kneale","sale_price":14702},
    {"id":3,"import_country":"Russia","model":"M","make":"Infiniti","sold_by":"Burl Pitkeathley","sale_price":18395}
  ],
  "Phillipines": [
    {"id":2,"import_country":"Philippines","model":"G-Class","make":"Mercedes-Benz","sold_by":"Gabie Gradwell","sale_price":19142}
  ]
}

Now that we have the data formatted how we would like, we can loop through it to get the total country count:

... // code from above
for (var country in map) {
   console.log(country + ": " + country.length + " cars");
}

That code would output:

Russia: 2 cars
Phillipines: 1 cars

Try below code -

var jsonArray = [{"id":1,"import_country":"Russia","model":"Express 2500","make":"Chevrolet","sold_by":"Sibylla Kneale","sale_price":14702},{"id":2,"import_country":"Philippines","model":"G-Class","make":"Mercedes-Benz","sold_by":"Gabie Gradwell","sale_price":19142},{"id":3,"import_country":"Russia","model":"M","make":"Infiniti","sold_by":"Burl Pitkeathley","sale_price":18395}];
var map = new Map();
for(var i=0;i<jsonArray.length;i++){
    if(!map.get(jsonArray[i].import_country)){
        map.set(jsonArray[i].import_country,1);
    }else{
        map.set(jsonArray[i].import_country, map.get(jsonArray[i].import_country) + 1);
    }
}

Pseudo Code:-

  1. Getting a JSON array.
  2. Creating an empty map.
  3. for i=0 to JSON Array length.

    a. if the map doesn't contain the country, then set the country with count 1.

    b. else set already existing key in the map by increasing with count 1.

  4. End.
Related