1

I have a JavaScript object like this:

[{"a":1,"b":2},{"a":1,"b":3},{"a":2,"b":4},{"a":2,"b":5}]

I want to group this object field 'a' and want something like this:

[{"a":1,"values":[{"a":1,"b":2},{"a":1,"b":3}]},{"a":2,"values":[{"a":2,"b":4},{"a":2,"b":5}]}]

I have a JavaScript array of more than few thousands elements. What is the most efficient way to achieve this?

sau
  • 1,316
  • 4
  • 16
  • 37

2 Answers2

1

Underscore JS provides nice methods for structuring your models and grouping/filtering them.

http://underscorejs.org/#groupBy

dubes
  • 5,324
  • 3
  • 34
  • 47
1

Try this code:

var data = [{"a":1,"b":2},{"a":1,"b":3},{"a":2,"b":4},{"a":2,"b":5}];

var res = alasql('SELECT a, ARRAY(_) AS [values] FROM ? GROUP BY a',[data]);

Here ARRAY(_) is a special aggregation function which saves current record(_) into the array with name values.

You can play with this example in jsFiddle.

agershun
  • 4,077
  • 38
  • 41