I have data in following format,
const data = [{
key:'key1',
rows:[
["A","2018","B","1"],
["A","2018","C","5"],
["A","2018","B","4"],
["A","2018","C","2"],
]
},
{
key:'key1',
rows:[
["A","2018","B","10"],
["A","2018","C","50"],
["A","2018","B","40"],
["A","2018","C","20"],
]
}]
I want to first reduce the rows and sum the last value in each array based on 3rd value. Output should be this,
const data = [{
key:'key1',
rows:[
["A","2018","B","5"],
["A","2018","C","7"]
]
},
{
key:'key1',
rows:[
["A","2018","B","50"],
["A","2018","C","70"]
]
}]
After this, I want to merge these 2 object and sum the value from rows. The final output should be this,
const data = [{
key:'key1',
rows:[
["A","2018","B","55"],
["A","2018","C","77"]
]
}]
I have tried this, but not getting desired output,
data.map(data => ({
...data,
rows: data.rows.reduce((array, value) => {
if(array.length > 0){
let found = false;
array.map(m => {
if(m[2] === value[2]){
found = true;
return [...m, m[3] = parseInt(m[3]) + parseInt(value[3])]
}
})
if(!found){
array.push(value)
}
return array
}else{
array.push(value)
return array
}
}, [])
}))
keyor are you merging regardless ofkey?