I want to compare 2 array of objects and update the matching object as well as total count in the object
let arr1 = [{status: 'Total', count: 0, text: 'Total applications'},
{status: 'submitted', count: 0, text: 'Applications submitted'},
{status: 'Rejected', count: 0, text: 'Applications rejected'}]
let arr2 = [
{status: "submitted", count: 20} ,
{status: "Rejected", count: 10}
]
function
let finalResult = arr2.map(function(a){
var result=arr1.filter(b=> a.status==b.status ? {...a, count:b.count} : arr1[0].count:arr1[0].count );
return result
})
Final Result should be like this:
[{status: 'Total', count: 30, text: 'Total applications'},
{status: 'submitted', count: 20, text: 'Applications submitted'},
{status: 'Rejected', count:10, text: 'Applications rejected'}
]
>Solution :
You can simply loop through second array and build a hash map and also find total value. now just loop over first array and update values accordingly
let arr1 = [{status: 'Total', count: 0, text: 'Total applications'},{status: 'submitted', count: 0, text: 'Applications submitted'},{status: 'Rejected', count: 0, text: 'Applications rejected'}]
let arr2 = [{status: "submitted", count: 20} ,{status: "Rejected", count: 10}]
let total = 0;
let obj = {}
// finding total and build hash map
arr2.forEach(data => {
obj[data.status] = obj[data.status] || data
total += data.count
})
// loop over first array and update count accordingly
let final = arr1.map(data => {
if(data.status === 'Total'){
return {...data, count: total}
} else if(data.status in obj){
return {...data, ...obj[data.status]}
} else {
return data
}
})
console.log(final)