Skip to content Skip to sidebar Skip to footer

Could Not Group By List Item In Javascript Object

I have a javascript object as below and i am trying to group by item. rfinOu=[ { 'pid': 34, 'ava': 30 }, { 'pid': 45, 'ava': 30 }, { 'pid': 32, 'ava': 60 }

Solution 1:

There is an alternative.

var out = rfinOu.reduce(function (p, c) {
  var key = c.ava;
  p[key] = p[key] || { count: 0, pids: [] };
  p[key].count++;
  p[key].pids.push(c.pid);
  return p;
}, {});

This will get you an object with ava keys:

{
  "30": { "count": 2, "pids": [ 34, 45 ] },
  "60": { "count": 1, "pids": [ 32 ] },
}

To get that into an array of objects like the one in your example, just loop over the object keys.

var arr = Object.keys(out).map(function(el) {
  return {
    ava: el, count: out[el].count,
    pids: out[el].pids
  }
});

To get the following output:

[
  { "ava": "30", "count": 2, "pids": [ 34, 45 ] },
  { "ava": "60", "count": 1, "pids": [ 32 ] },
]

DEMO


Solution 2:

Here you have an example code with a Pids Array instead an Object:

var rfinOu=[
  { "pid": 34, "ava": 30 },
  { "pid": 45, "ava": 30 },
  { "pid": 32, "ava": 60 }
];

var final = [];
var indexes = {};
var position;

rfinOu.forEach(function(item){

  if( indexes.hasOwnProperty(item.ava) ){

    final[indexes[item.ava]].count++;
    final[indexes[item.ava]].Pids.push(item.pid);

  }else{

    position = final.length;

    indexes[item.ava] = position;

    final[position] = {ava: item.ava, count: 1};
    final[position].Pids = [item.pid]; 

  }

});

console.log(final);

jsfiddle


Post a Comment for "Could Not Group By List Item In Javascript Object"