I have an array of object as
arr1 = [{catid: 1, name: 'mango', category: 'fruit'}, {catid: 2 name: 'potato', category: 'veg'}, {catid: 3, name: 'chiken', category: 'nonveg'},{catid: 1, name: 'apple', category: 'fruit'}, {catid: 1, name: 'banana', category: 'fruit'}];
I want to convert the above array to 2-d array based on catid of the element(basically want to group all elements on the basis of same catid):
arr2 = [[{catid: 1, name: 'mango', category: 'fruit'},{catid: 1, name: 'apple', category: 'fruit'}, {catid: 1, name: 'banana', category: 'fruit'} ],[{catid: 2 name: 'potato', category: 'veg'}],[{catid: 3, name: 'chiken', category: 'nonveg'}]]
How can I do this in typescript or javascript.
2
Answers
You can do it with
Object.groupBy()
:You could also use
Array#reduce()
:Playground
As an alternative, a
for loop
can be used;