javascript - Angular: How to get the count of the Object with specific value? -


i have json database objects. each 1 has properties specific assigned value: a, b or c.

[   {     "id": 1,     "category": "a"   },   {     "id": 2,     "category": "b"   },   {     "id": 3,     "category": "c"   },   {     "id": 4,     "category": "a"   },   {     "id": 5,     "category": "a"   },   {     "id": 5,     "category": "b"   } ] 

i want display like:

there total of 6 items: x 3, b x 2 , c x 1.

i know have use objectsinmyjsondatabase.length total.

i'm wondering how possible length (number) of objects have specific value?

one way solve problem use map-reduce. here quick solution. hope solve problem.

var data = [    {      "id": 1,      "category": "a"    },    {      "id": 2,      "category": "b"    },    {      "id": 3,      "category": "c"    },    {      "id": 4,      "category": "a"    },    {      "id": 5,      "category": "a"    },    {      "id": 5,      "category": "b"    }  ];    // first list of categories  var categories = data.map(function(x) { return x["category"]; });    // count no of items in each category  var countbycategories = categories.reduce(function(x, y) {      if (typeof x !== "object") {         var reduced = {};         reduced[x] = 1;         reduced[y] = 1;         return reduced;      }            x[y] = (x[y] || 0) + 1;      return x;  });    // final build string want  var categorystrings = [];  (var category in countbycategories) {     categorystrings.push(category + ' x ' + countbycategories[category]);   }    var msg = 'there total of ' + categories.length + ' items: ';  if (categorystrings.length > 2) {     msg = categorystrings.slice(0, -1).join(', ');      msg += ' , ' + categorystrings.slice(-1);  } else {     msg = categorystrings.join(', ');   }    // print results  console.log(msg);


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -