如何在javascript中根据日期(或任何类似的元素)合并数组中的两个元素?

问题描述 投票:0回答:1

我现在的数组是这样的

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

所以我们的想法是对那些重复的日子进行加总和过滤,就像上面的数组一样,第12天是重复的,所以我们对小时数进行加总,结果应该是这样的。

array = [
 {
  date: '2020/06/12',
  hours: 12.2
 },
 {
  date: '2020/06/15',
  hours: 4.5
 },
 {
  date: '2020/06/16',
  hours: 5.5
 },
]
javascript arrays lodash
1个回答
4
投票

你可以使用减速器。

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;
}
, []);

0
投票

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);
© www.soinside.com 2019 - 2024. All rights reserved.