Alex Alex - 2 months ago 5
Javascript Question

Get unique value from array of objects

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?

Answer
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.

Comments