I have the following array a as shown below:
var a = [
{name: 'phone' , id:1 ,num:1},
{name: 'milk' ,id:2, num:1},
{name: 'apple' , id:3 , num:1},
{name: 'phone', id: 4, num:3},
]
I want to filter by array name and add their own num
var currentName = a[0]
let newArrys=[]
for(let i = 0; i<a.length;i++){
if(currentName.name == a[i].name){
a[i].num = a[i].num + currentName.num
let tmepArry = [];
tempArry.push(a[i]);
newArrys.push(tempArry);
}
}
I am trying to obtain the following 2D array:
[
[{name: 'phone', id:1, num:4}],
[{name: 'milk',id:2, num:1}],
[{name: 'apple', id: 3 num:1}]
]
The result cannot be screened out.
My attempt is invalid.
Can you help me?
Array.reducefor this.