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

187
Views
How to compress duplicate elements and get their quantity values?

I need to find the elements with the same id in the array below, add their amounts and write them in a single line.

 let arr = [
{ itemId: 123, name: '0', quantity: 2 },
{ itemId: 1, name: '1', quantity: 2 },
{ itemId: 13, name: '2', quantity: 2 },
{ itemId: 13, name: '3', quantity: 2 },
{ itemId: 13, name: '4', quantity: 24 },
{ itemId: 13, name: '5', quantity: 2 },
{ itemId: 1, name: '6', quantity: 4 },
{ itemId: 1, name: '7', quantity: 2 },];
  

I want an output like this:

[{ itemId: 123, name: '1', quantity: 2 },
{ itemId: 1, name: '2', quantity: 6 },
{ itemId: 13, name: '6', quantity: 30 }];

And my code:

const getPureList = () => {
    for (let index = 0; index < arr.length; index++) {
      for (let a = index + 1; a < arr.length; a++) {
        if (arr[index].itemId === arr[a].itemId) {
          arr[index].quantity += arr[a].quantity;
          arr.splice(a, 1);
        }
      }
    }
    return arr;
  };

Thanks for your help.

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

0

By keeping the name od the first object of the group, you could take an object for grouping and take the values as result.

const
    array = [{ itemId: 123, name: '0', quantity: 2 }, { itemId: 1, name: '1', quantity: 2 }, { itemId: 13, name: '2', quantity: 2 }, { itemId: 13, name: '3', quantity: 2 }, { itemId: 13, name: '4', quantity: 24 }, { itemId: 13, name: '5', quantity: 2 }, { itemId: 1, name: '6', quantity: 4 }, { itemId: 1, name: '7', quantity: 2 }],
    result = Object.values(array.reduce((r, o) => {
        r[o.itemId] ??= { ...o, quantity: 0 };
        r[o.itemId].quantity += o.quantity;
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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!