I have got an array of objects of the form:
[
{
"id": "id_1",
"type": "A",
"value": "value_1",
"label": "label_1"
},
{
"id": "id_2",
"type": "B",
"value": "value_2",
"label": "label_2"
},
{
"id": "id_3",
"type": "C",
"value": "value_3",
"label": "label_3"
},
{
"id": "id_4",
"type": "A",
"value": "value_4",
"label": "label_4"
}
]
This needs to become an array of arrays. Where The arrays are grouped by type. And the id field can be omitted.
So I should end up with:
[
[
{
"value": "value_1",
"label": "label_1"
},
{
"value": "value_4",
"label": "label_4"
}
],
[
{
"value": "value_2",
"label": "label_2"
}
],
[
{
"value": "value_3",
"label": "label_3"
}
]
]
I want to avoid using loops if possible. Any help would be greatly appriciated!
compareToand sort the original array. Then you only need to iterate once over the original array (looping, streaming...iterating) and for every element you check if it belongs to the previous sub array or if you need to create a new one.