Nicolas Silva
Nicolas Silva

Reputation: 639

how do i merge two elements from array in javascript depending on the date (or whatever the element is similar to)

my current array looks like this

array = [
 {
  date: '2020/06/12',
  hours: 8.4
 },
 {
  date: '2020/06/15',
  hours: 4.5
 },
 {
  date: '2020/06/12',
  hours: 3.8
 },
 {
  date: '2020/06/16',
  hours: 5.5
 },
]

so the whole idea is to sum and filter those days that are repeated, like the array from above, the day 12 is duplicated, so we sum the hours, the result should be like this

array = [
 {
  date: '2020/06/12',
  hours: 12.2
 },
 {
  date: '2020/06/15',
  hours: 4.5
 },
 {
  date: '2020/06/16',
  hours: 5.5
 },
]

Upvotes: 0

Views: 53

Answers (2)

Lahiru Tennakoon
Lahiru Tennakoon

Reputation: 649

const groupBy = (arrayOfObjects, property) => {
  let i = 0;
  let val;
  let index;
  const values = [];
  const
    result = [];
  for (; i < arrayOfObjects.length; i++) {
    val = arrayOfObjects[i][property];
    index = values.indexOf(val);
    if (index > -1) result[index].push(arrayOfObjects[i]);
    else {
      values.push(val);
      result.push([arrayOfObjects[i]]);
    }
  }

  const newArray = [];

  for (const x of result) {
    let total = 0;
    let datex;
    for (const obj of x) {
      datex = obj.date;
      total += obj.hours;
    }

    newArray.push({
      date: datex,
      hours: total,
    });
  }

  return newArray;
};

// Call the groupBy function
const answer = groupBy([{
    date: '2020/06/12',
    hours: 8.4
  },
  {
    date: '2020/06/15',
    hours: 4.5
  },
  {
    date: '2020/06/12',
    hours: 3.8
  },
  {
    date: '2020/06/16',
    hours: 5.5
  },
], "date");

console.log(answer);

Upvotes: 0

Berk Kurkcuoglu
Berk Kurkcuoglu

Reputation: 1523

You can use a reducer:

const result = array.reduce((acc, cur) => {
   const prev = acc.find(elem => elem.date === cur.date);
    if(prev) {
        prev.hours += cur.hours;
    } 
    else {
        acc.push(cur);
    }
    return acc;
}
, []);

Upvotes: 4

Related Questions