2

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.

1
  • Can you add the expected result? Commented May 18, 2020 at 14:33

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

where is the code to increment the count of countries?
Ah good point @AmanKumayu - I interpreted as getting the total number of cars per country, not just the total countries.
1

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.

2 Comments

Thank you! I see each country from my API with the correct key-value pair.
Something shortter : countries.map(v => v.import_country).filter((v, i, a) => a.indexOf(v) !== i).length);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.