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

82
Views
Count array with matching data then push to new array

I need to figure out how to count an array then combine only the matching ones.

example

const info = [ { name: 'John', date:'2022-04-11', type: '2', time: 5.00 },
               { name: 'Dave', date:'2022-04-12', type: '3', time: 6.00 },
               { name: 'John', date:'2022-04-11', type: '2', time: 2.00 },
               { name: 'John', date:'2022-04-15', type: '2', time: 3.00 } ];

The expected result should check for the same type, name and date them combine time. and the new array should look something like this.

It can be done with a forloop, but I would like to try creating a solution with es6.

But I am a bit unsure how to approach this.

const expected = [ { name: 'John', date:'2022-04-11', type: '2', time: 7.00 },
                     name: 'Dave', date:'2022-04-12', type: '3', time: 6.00 },
                     name: 'John', date:'2022-04-15', type: '2', time: 3.00 } ];
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You could use a combination of .reduce and .find

const info = [ { name: 'John', date:'2022-04-11', type: '2', time: 5.00 },
               { name: 'Dave', date:'2022-04-12', type: '3', time: 6.00 },
               { name: 'John', date:'2022-04-11', type: '2', time: 2.00 },
               { name: 'John', date:'2022-04-15', type: '2', time: 3.00 } ];


const result = info.reduce((acc, x) => {
  const foundObj = acc.find(y => y.name === x.name && y.date === x.date && y.type === x.type);
  if (foundObj) {
    foundObj.time += x.time;
  } else {
    acc.push(x);
  }
  return acc;
}, []);
console.log(result)

about 4 years ago · Santiago Trujillo Report

0

You could for example create an object, where the key is a combination of name, date, type and the value is time

  let grouped = info.reduce((acc, curr) => {
  let key = `${curr.name}${curr.date}${curr.type}`;
  if (!acc[key]) {
    acc[key] = {
      name: curr.name,
      date: curr.date,
      type: curr.type,
      time: curr.time,
    };
  } else {
    acc[key].time += curr.time;
  }
  return acc;
}, {});

let expected = Object.values(grouped);
about 4 years ago · Santiago Trujillo 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!