How to sort data and measure length by key value using Javascript

advertisements

I need one help.I have some array of data i need to sort the as per key value and measure the length.I am explaining my code below.

var response = [{
      day_id:1,
      day_name:"Monday",
      subcat_id:"2",
      cat_id:"1",
      comment:"hii"
}, {
      day_id:1,
      day_name:"Monday",
      subcat_id:"1",
      cat_id:"2",
      comment:"hello"
}
 {
      day_id:2,
      day_name:"Tuesday",
      subcat_id:"3",
      cat_id:"2",
      comment:"hii"
}]

Here for day_id=1 there are two set of data and same for day_id=2 present.I need to measure length of data set present as per day_id e,g.for day_id=1 length is 2Please help me.


You can map response and save in an object how many times each id was seen:

var counter = {};
response.map(function(item) {
    counter[item.day_id] = (counter[item.day_id] || 0) + 1;
});

Your results are in counter:

console.log(counter);
// { '1': 2, '2': 1 }

Hope it helps.