SimpleOne
SimpleOne

Reputation: 1076

underscore js - indexBy / countBy multiple values

If I had the following register and want to summarise it by date.

var register = [
{date: '24/12/2015', present: 'P'}, 
{date: '24/12/2015', present: 'A'}, 
{date: '24/12/2015', present: 'P'}, 
{date: '25/12/2015', present: 'P'}, 
{date: '25/12/2015', present: 'P'}];

The result I am looking for is something like below (doesn't have to be exactly this format so long as I can get the summary data in some format - multi dimension array or array of objects is fine). Ultimately I was hoping to use chart.js to show the attendance by date.

'24/12/2015': {P: 2, A: 1},
'25/12/2015': {P: 2, A: 0}

In the above the numbers are the count of 'P' and 'A' for each given date.

I am not sure how to do this using underscore js - I think it can be done using indexBy and countBy but not really sure!

Upvotes: 2

Views: 812

Answers (2)

Bek
Bek

Reputation: 3207

this can be achieved without underscore

var register = [
{date: '24/12/2015', present: 'P'}, 
{date: '24/12/2015', present: 'A'}, 
{date: '24/12/2015', present: 'P'}, 
{date: '25/12/2015', present: 'P'}, 
{date: '25/12/2015', present: 'P'}];

var counted = register.reduce(function(sum, item) {
  var date = item.date;
  var present = item.present;

  if (sum[date]) {
    if (sum[date][present]) {
      sum[date][present] = sum[date][present] + 1;
    } else {
      sum[date][present] = 1;
    }
  } else {
    sum[date] = {};
    sum[date][present] = 1;
  }
  return sum;
}, {})

snippet.log(counted)
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Upvotes: 1

Alexander Mikhalchenko
Alexander Mikhalchenko

Reputation: 4565

Simply use the reduce function

register.reduce(function(memo, item){
  if(!memo.hasOwnProperty(item.date)){
    memo[item.date] = { P:0, A:0 };
  }    
  memo[item.date][item.present]++;
  return memo;
}, {});

Upvotes: 3

Related Questions