I'm attempting to reverse the flattening process of an array.
The JSON array I have as input contains 4 elements:
[
{
"nestedObj": {
"id":12
}
},
{
"nestedObj": {
"id":555
}
},
{
"nestedObj": {
"id":555
}
},
{
"nestedObj" :{
"id":771
}
}
]
I aim to convert it into an array of arrays, with each sub-array containing elements grouped by their nestedObj.id
.
The initial JSON is assumed to be sorted by nestedObj.id
.
In the example above, since the id
of nestedObj
for the 2nd and 3rd elements are the same (555
), they will be grouped together in one sub-array.
The resulting array will consist of only 3 sub-array elements:
[
[{
"nestedObj": {
"id":12
}
}],
[{
"nestedObj": {
"id":555
}
},
{
"nestedObj": {
"id":555
}
}],
[{
"nestedObj" :{
"id":771
}
}]
]
This code provides the desired output:
const data = [ /* ...the above input data... */ ];
let result = [];
let prevId = null;
for (let elem of data) {
let currId = elem.nestedObj.id;
if (currId === prevId) {
result[result.length - 1].push({...elem});
} else {
result.push([{...elem}]);
}
prevId = currId;
}
However, the code is quite verbose. It lacks the elegance of modern JavaScript techniques like 'reduce' or other functional programming approaches. Can anyone suggest a sleeker rewrite?