我现在的数组是这样的
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
},
]
你可以使用减速器。
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;
}
, []);
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);