Home > front end >  Count array with matching data then push to new array
Count array with matching data then push to new array

Time:04-12

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 } ];

CodePudding user response:

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

CodePudding user response:

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)

  • Related