Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
group the object in array by name
let obj = [
    {
        name: "a",
        quantity: 2
    },
    {
        name: "b",
        quantity: 4
    },
    {
        name: "c",
        quantity: 88
    }
]

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

I want to group two object array but if object which has a same name already exists then merge.

For example, there are objects which name is "a" and I want to merge them together.

Output what I want is like

[
    {
        name: "a",
        quantity: 4
    },
    {
        name: "b",
        quantity: 4
    },
    {
        name: "c",
        quantity: 88
    }
]

The quantity of object which name is "a" is add together. Is there anyway to do this?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

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

let obj3 = [...obj, ...obj2];

let obj4 = obj3.reduce( (curr, ele) => {
  let exist = curr.filter( cur => cur.name == ele.name)
  if (exist.length) exist[0].quantity += ele.quantity
  else curr.push({...ele})
  return curr
}, [])

let obj5 = Object.values(
  obj3.reduce((res, {name, quantity}) => {
    let ele = res[name] ??= {name}
    ele['quantity'] = (ele['quantity'] ?? 0) + quantity
    return res
  }, {})
)
console.log(obj4, obj5)

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!