John
John

Reputation: 634

Group objects based on a id, and create a array of ojects

From an ajax request I get this array of objects:

0: Object
  group_id: 2
  group_name: "Name1"
  rez: 1
1: Object
  group_id: 2
  group_name: "Name1"
  rez: 3
2: Object
  group_id: 3
  group_name: "Name2"
  rez: 1
3: Object
  group_id: 3
  group_name: "Name2"
  rez: 2

I would like to group those values based on their group_id, and produce an array of objects which looks like this.

[{name: 'Name1', data: [1 ,3]}, {name: 'Name2', data: [1, 2]}]

Whats the best way of doing this?

Upvotes: 0

Views: 56

Answers (1)

bvx89
bvx89

Reputation: 888

Assuming that the array will come in an correct order, and that group_id always results in the same group_name, you can generate the objects you want with this algorithm:

var out = []; 
for (var j in arr) {
  var obj = arr[j];

  var last = out[out.length-1];
  if (last != undefined && last.name == obj.group_name) {
    var data = last.data;
    data.push(obj.rez);

    out[out.length-1].data = data;
  } else {
    var newObj = {name: obj.group_name, data: [obj.rez]};
    out.push(newObj);
  }
}

Note: The array you recieve is given the variable name arr in this example.

Upvotes: 1

Related Questions