3

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.

  • sort you have here http://stackoverflow.com/questions/14208651/javascript-sort-key-value-pair-object-based-on-value – daremachine Mar 19 '16 at 03:47

2 Answers2

2

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.

0

Do not use .map, use .forEach as it doesn't return another array

and the code could be a little cleaner:

var counter = {};
response.forEach(function(item) {
    counter[item.day_id] = ++counter[item.day_id] || 1;
});
omarjmh
  • 13,632
  • 6
  • 34
  • 42