I am receiving the following array from an API response:
[
{group: '1', , value: 'a'}
{group: '1', , value: 'b'}
{group: '2', , value: 'c'}
{group: '2', , value: 'd'}
]
I want to convert it to the following (want order of groups as received, values can be ordered in any way):
[
{group: '1', values: ['b', 'a'] },
{group: '2', values: ['c', 'd'] },
]
Which Javascript function will be the most efficient to convert it?
I am able to do this by:
let result = [];
data.reduce((groupNumber, input) => {
if (!groupNumber[input.group]) {
groupNumber[input.group] = {group: input.group, values: []};
result.push(groupNumber[input.group]);
}
groupNumber[input.group].values.push(input);
return groupNumber;
}, {});
Is reduce
the correct function to be used here? Is there a more efficient approach?
Secondly, will reduce
preserve the order in the result? If I am actually receiving the data with group 1 entries first, group 2 next, and so on, can I rely on result
being ordered similarly?
Note that I only care about the order of the groups, not about the values inside the group.