I have a heavy array like this:
[ {Id: 1, Name: 'Red', optionName: 'Color'}, {Id: 2, Name: 'Yellow', optionName: 'Color'}, {Id: 3, Name: 'Blue', optionName: 'Color'}, {Id: 4, Name: 'Green', optionName: 'Color'}, {Id: 7, Name: 'Black', optionName: 'Color'}, {Id: 8, Name: 'S', optionName: 'Size'}, {Id: 11, Name: 'M', optionName: 'Size'}, {Id: 12, Name: 'L', optionName: 'Size'}, {Id: 13, Name: 'XL', optionName: 'Size'}, {Id: 14, Name: 'XXL', optionName: 'Size'} ]
I need to group by optionName
and have two rows in the main array, like this:
[ { Name: 'Color', Data:[{Id: 1, Name: 'Red'}, {Id: 2, Name: 'Yellow'}, {Id: 3, Name: 'Blue'}, {Id: 4, Name: 'Green'}, {Id: 7, Name: 'Black'}] }, { Name: 'Size', Data:[{Id: 8, Name: 'S'}, {Id: 11, Name: 'M'}, {Id: 12, Name: 'L'}, {Id: 13, Name: 'XL'}, {Id: 14, Name: 'XXL'}] } ]
How to implement it in javascript?
An ES6 solution using Map object:
Here is the code snippet I wrote for this situation. You can add this function to all arrays:
You can use it like this. You just pass a function that defines how to group the data.
Working Fiddle
If necessary, you can replace
{key: k, data: map[k]}
with{Name: k, Data: map[k]}
.This is also a more compact ES6 version of the above code:
Use it like this: