Merge Array of Objects by Same Key-Value

Merging objects from array with the same key value

You could use reduce with Object.keys to do that.

var arr = [
{id: 1, tech_id:11, action: 'swim'},
{id: 2, tech_id:11, action: 'run'},
{id: 3, tech_id:22, action: 'climb'},
{id: 4, tech_id:22, action: 'swim'},
{id: 5, tech_id:11, action: 'jump'},
]

let mergeObj = arr.reduce((p, c) => {
const {tech_id, ...otherData} = c;

if (!(tech_id in p)) {
p[tech_id] = {
data: []
}
}

p[tech_id].data.push(otherData)
return p
}, {})

mergeObj = Object.keys(mergeObj).map(key => {
return {
tech_id: key,
data: mergeObj[key].data
}
})

console.log(mergeObj);

group the object in array by name

You can use forEach() for this.

let obj = [
{
name: "a",
quantity: 2
},
{
name: "b",
quantity: 4
},
{
name: "c",
quantity: 88
}
]

let obj2 = [
{
name: "a",
quantity: 2
}
]

obj.forEach((element)=>{
obj2.forEach((e)=>{
if(element.name == e.name){
element.quantity = element.quantity+e.quantity
}
})
})

console.log(obj);

Merge two arrays of objects with the same keys in JavaScript

Your third try [arr1, arr2] was really close to a right answer, you can use the new spread syntax (...) to concat the arrays by doing to following: