I have the following array:
[
{
"level": "level3",
"category": "car"
},
{
"level": "level1",
"category": "bike"
},
{
"level": "level2",
"category": "car"
},
{
"level": "level5",
"category": "bike"
}
]
I need to convert this to the following object:
newObj = {
car: ['level3', 'level2'],
bike: ['level5', 'level1'],
};
What would be the best way to achieve this? Thanks in advance
3
Answers
You could achieve what you want with many approaches:
for...of
approachreduce
approachThe first approach is simple and understandable and the second is a more functional approach. But both approaches have a linear time complexity of O(n), choosing one of them is just a matter of personal preference and coding style.
By using the function
Array.prototype.reduce
An old-school imperative approach with a linear runtime (that is double the size of your array, and you double the time it takes for the algorithm to finish)
Also, it’s a good idea to watch for the presence of the fields
category
and
level
.