Vec*_*yte 5 javascript arrays object
我在一个数组中有 3 个对象,其中所有对象都具有相同数量的数据属性。数据如下:
const monthStats = [{
name: 'pending',
data: ['5', '1', '2', '3', '100', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '20', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'],
}, {
name: 'delivered',
data: ['10', '44', '12', '0', '250', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '180', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'],
}, {
name: 'failed',
data: ['15', '33', '30', '2', '150', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '50', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'],
}];
Run Code Online (Sandbox Code Playgroud)
数据表示一个月中的日期值(因此它们的长度相等)。我想要的是获取每个日期的替代数据值的总和并从中获取最大值。
替代在这里意味着例如:待定第 0 个索引的值为 5,类似地,交付时为 10,失败时为 15。它们的总和为30。在这里,上面例子中的最大值500在对它们求和后的第 4 个索引上,这就是我想要的。
我怎样才能做到这一点?
Here is what you want as per my understanding:
Run Code Online (Sandbox Code Playgroud)
Here is what you want as per my understanding:
Run Code Online (Sandbox Code Playgroud)
假设待处理、已交付和失败的对象保持该顺序(这不是一个好的做法,但是......好吧)。
您可以简单地将数据数组的每个值的元素相加,然后获取该总和的最大值,然后获取该最大值的索引。
const monthStats = [{
name: 'pending',
data: ['5', '1', '2', '3', '100', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '20', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'],
}, {
name: 'delivered',
data: ['10', '44', '12', '0', '250', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '180', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'],
}, {
name: 'failed',
data: ['15', '33', '30', '150', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '50', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'],
}];
const monthTotals = monthStats[0].data.map((pend, pIndex) => Number(pend) + Number(monthStats[1].data[pIndex]) + Number(monthStats[2].data[pIndex]));
const maxMonthTotal = Math.max(...monthTotals);
const maxMonthTotalIndex = monthTotals.findIndex(monthTotal => maxMonthTotal === monthTotal);
console.log('MonthStats the max is: ', maxMonthTotal, ' on the position: ', maxMonthTotalIndex + 1)
console.log('MonthStats totals', monthTotals);Run Code Online (Sandbox Code Playgroud)