Search code examples
javascriptarraysdictionaryfunctional-programmingmap-function

Aggregate and transform array of objects


Using javascript functional programming methods (like map/reduce), how would one aggregate/count the status field of arr1 and transform it to an array of key/value objects in arr2.

arr1 = [
  {'task':'do something 1', 'status':'done'} , 
  {'task':'do something 2', 'status':'done'} , 
  {'task':'do something 3', 'status':'pending'} , 
  {'task':'do something 4', 'status':'done'}
];

// Aggregate arr1 `status` field and transform to:

arr2 = [
  {key:'done', value: 3},
  {key:'pending', value: 1}
];

Here's my WIP partial solution that handles only the aggregation portion. I still need the transform portion.

var arr2 = arr1.map(function(item) {
    return item.status;
  }).reduce(function(acc,curr,idx){
    if(acc[curr] === undefined) acc[curr] = 1;
    else acc[curr] += 1;
    return acc;
  }, []); 

Solution

  • Here's the most functional way I could come up with. This includes both the aggregation and your desired transform:

    var arr2 = Object.keys(arr2 = arr1.map(function(item) {
        return item.status;
    }).reduce(function(acc,curr){
        acc[curr] = acc[curr] + 1 || 1;
        return acc;
    }, [])).map(function(item){
        return {key: item, value: arr2[item]}
    });