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?

3
  • 2
    Possible duplicate of array_count_values for JavaScript instead Commented Sep 20, 2016 at 11:12
  • Did you try to create a function that takes Country name and cars produced as arguments, then call it at the end of each for loop? Commented Sep 20, 2016 at 11:12
  • @Alex the duplicated flagged question is exactly what you are looking for. Commented Sep 20, 2016 at 11:15

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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.