0

I have the following code:

        fetchDemo(carMakesUrl).then(function(result) {
            for(var i = 0; i < result.length; i++){
                for(var prop in result[i]){
                    if(prop.length > 1){
                        console.log(result[i]['make_country']);
                    }
                }
            }
        });

and "carMakesUrl" is equal to "https://rawgit.com/csabapalfi/20d74eb83d0be023205225f79d3e7964/raw/7f08af5c0f8f411f0eda1a62a27b9a4ddda33397/carmakes.json"

what I am getting back is something like this:

4 Italy
4 UK
4 USA
4 Italy
8 UK
4 Germany
4 UK
4 USA
16 UK
4 Germany
8 UK
4 Italy
4 France
the list carries on..

what I am looking for is something like:

Italy is repeated 17 times which means that "it produces 17 types of cars" and so other countries will produce a number of different cars...

How can I console.log so that it only outputs the country name once and with the number of cars it produces?

Aessandro
  • 5,517
  • 21
  • 66
  • 139

2 Answers2

1
fetchDemo(carMakesUrl).then(function(result) {    
  var obj = {};
  result.forEach(function(ele,ind){obj[ele.make_country] = (obj[ele.make_country] || 0) + 1});
  console.log(obj);
});

You can take the count like this.

AB Udhay
  • 643
  • 4
  • 9
1

I have assumed that the obj=result. Hope this will work for you. And country_car_counter object hold the required output

var country_car_counter = {};
      obj.map(function(item){
        var property = item.make_country;

         country_car_counter[property] = (country_car_counter[property])?country_car_counter[property] + 1 : 1 ;

      })
      console.log('this is the required object',country_car_counter)
Vishnu Shekhawat
  • 1,245
  • 1
  • 10
  • 20