Sort continents by amount of countries

378 views Asked by At

I have a list of countries:

"country": [
       {
           "countryCode": "AD",
           "countryName": "Andorra",
           "currencyCode": "EUR",
           "population": "84000",
           "capital": "Andorra la Vella",
           "continentName": "Europe",
           "continent": "EU",
           "areaInSqKm": "468.0",
           "languages": [
               "ca"
           ]
       },
       {
           "countryCode": "AE",
           "countryName": "United Arab Emirates",
           "currencyCode": "AED",
           "population": "4975593",
           "capital": "Abu Dhabi",
           "continentName": "Asia",
           "continent": "AS",
           "areaInSqKm": "82880.0",
           "languages": [
               "ar-AE",
               "fa",
               "en",
               "hi",
               "ur"
           ]
       },
etc.

Now I have to write a Map/Reduce function in JSON to get an output like this:

Key: Afrika Value: xxx Key: Asia Value: xxx Etc.

Where 'value' represents the amount of countries in each continent.

I already tried this Map function:

function(doc) {
   var a
   {
      for (a in doc.country){
         emit(doc.country[a].continentName, 1)
      };
   }
}
2

There are 2 answers

0
Ingo Radatz On

I recommend to emit the value null instead of 1 and use the built-in reduce function _count.

0
Jurgen On

Map Function:

function(doc) {
    var country = doc.country;
    var i;
        for (i in country) {
            emit (country[i].continentName, 1)
        };
}

And then you have to reduce it with the Reduce Function:

function(keys, values) {
   return sum(values);}