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

72
Views
Combing Variables with Same Id

I'm working on a project where i am trying to get array with all 50 US states. I have some data where the id is the abbreviated version of the state and some where the id is the name of the state. I want all of the data to be under an id that is equal to the name of the state.

For this, I have:

let Array9 = (orderLocationUS);
    
 Array9.forEach((state) => {
            if (state._id === 'NY' || state._id === 'New York' || state._id === 'ny' || state._id === 'N.Y.' ){
               state._id = 'New York'     
        }})
console.log(orderLocationUS)

console.log(orderLocationUS) gives:

[
  { _id: 'New York', count: 1, totalSales: 108.75 },
  { _id: 'New Jersey', count: 1, totalSales: 100 },
  { _id: 'New York', count: 31, totalSales: 627.93 }
]

I want the result:

[
  { _id: 'New Jersey', count: 1, totalSales: 100 },
  { _id: 'New York', count: 32, totalSales: 736.68 }
]

I tried to get the count by:

array10 = = orderLocationUS.filter((state) => state._id === 'New York').map(x => x.count).reduce((a, b) => a + b, 0)
console.log(array10)

This does give me 32, but I need this in an array format and I know this is probably not the right way to get the results I need. I would really appreciate suggestion on how to get the:

[
  { _id: 'New Jersey', count: 1, totalSales: 100 },
  { _id: 'New York', count: 32, totalSales: 736.68 }
]

array that I need.

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

0

Use includes to check if existing then just add if already present.

function combine() {
  let array = [{
      _id: 'New York',
      count: 1,
      totalSales: 108.75
    },
    {
      _id: 'New Jersey',
      count: 1,
      totalSales: 100
    },
    {
      _id: 'New York',
      count: 31,
      totalSales: 627.93
    }
  ];
  let output = [];

  array.forEach(function(item) {
    let existing = output.filter(function(v, i) {
      return v._id == item._id;
    });
    if (existing.length) {
      let existingIndex = output.indexOf(existing[0]);
      output[existingIndex].totalSales += item.totalSales;
      output[existingIndex].count += item.count;
    } else
      output.push(item);
  });
  console.log(output);
}

combine();

output

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!