STORM STORM - 3 months ago 9
AngularJS Question

How to get row count for a items with value x in AngularJS?

I have the following object

var countries = [
{country: "Ireland", continent: "Europe", language: "English"},
{country: "Spain", continent: "Europe", language: "Spanish"},
{country: "United Kingdom", continent: "Europe", language: "English"},
{country: "France", continent: "Europe", language: "French"},
{country: "Germany", continent: "Europe", language: "(other)"},
{country: "Sweden", continent: "Europe", language: "(other)"},
{country: "Norway", continent: "Europe", language: "(other)"},
{country: "Italy", continent: "Europe", language: "(other)"},
{country: "Greece", continent: "Europe", language: "(other)"},
{country: "Iceland", continent: "Europe", language: "(other)"},
{country: "Portugal", continent: "Europe", language: "Portuguese"},
{country: "Malta", continent: "Europe", language: "(other)"},
{country: "Brazil", continent: "South America", language: "Portuguese"},
{country: "Argentina", continent: "South America", language: "Spanish"},
{country: "Colombia", continent: "South America", language: "Spanish"},
{country: "Peru", continent: "South America", language: "Spanish"},
{country: "Venezuela", continent: "South America", language: "Spanish"},
{country: "Uruguay", continent: "South America", language: "Spanish"}
];


How can I count the objects with for example
continent
=== 'South America' ? It is a JSON list of obejcts returned from a WebService within an AngularJS Controller.

Answer

You can use Array#reduce()

var countries = [{"country":"Ireland","continent":"Europe","language":"English"},{"country":"Spain","continent":"Europe","language":"Spanish"},{"country":"United Kingdom","continent":"Europe","language":"English"},{"country":"France","continent":"Europe","language":"French"},{"country":"Germany","continent":"Europe","language":"(other)"},{"country":"Sweden","continent":"Europe","language":"(other)"},{"country":"Norway","continent":"Europe","language":"(other)"},{"country":"Italy","continent":"Europe","language":"(other)"},{"country":"Greece","continent":"Europe","language":"(other)"},{"country":"Iceland","continent":"Europe","language":"(other)"},{"country":"Portugal","continent":"Europe","language":"Portuguese"},{"country":"Malta","continent":"Europe","language":"(other)"},{"country":"Brazil","continent":"South America","language":"Portuguese"},{"country":"Argentina","continent":"South America","language":"Spanish"},{"country":"Colombia","continent":"South America","language":"Spanish"},{"country":"Peru","continent":"South America","language":"Spanish"},{"country":"Venezuela","continent":"South America","language":"Spanish"},{"country":"Uruguay","continent":"South America","language":"Spanish"}]
    
var result = countries.reduce(function(r, e) {
  if(e.continent === 'South America') r++
  return r;
}, 0);

console.log(result)