假设我有一个像这样的对象数组:
const data = [
{ value: 0.35, name: 'a' },
{ value: 0.12, name: 'b' },
{ value: 0.05, name: 'c' },
{ value: 0.25, name: 'd' },
{ value: 0.23, name: 'e' },
]
总和正好是 1.0。
这是我想要得到的结果:
const data = [
{ value: 0.35, name: 'a', cumulativeValue: 0.35 },
{ value: 0.12, name: 'b', cumulativeValue: 0.47 },
{ value: 0.05, name: 'c', cumulativeValue: 0.52 },
{ value: 0.25, name: 'd', cumulativeValue: 0.48 },
{ value: 0.23, name: 'e', cumulativeValue: 0.23 },
]
逻辑是累加直到总和超过50,一旦超过这个值就从数组末尾开始计算累加值。
这是我的代码,它可以工作,但是有没有更优雅的方法来做到这一点?
const data = [
{ value: 0.35, name: 'a' },
{ value: 0.12, name: 'b' },
{ value: 0.05, name: 'c' },
{ value: 0.25, name: 'd' },
{ value: 0.23, name: 'e' },
]
function computeCumulative(data) {
const newData = data.reduce((prevWithCumPercentages, datum, i) => {
const cumulativeParcentage = i === 0 ? 0 : prevWithCumPercentages[i - 1].cumulativePercentageL
const newDatum = {
...datum,
cumulativePercentageL: datum.value + cumulativeParcentage,
}
prevWithCumPercentages.push(newDatum)
return prevWithCumPercentages
}, [])
const dataReverse = [...data].reverse().reduce((prevWithCumPercentages, datum, i) => {
const cumulativeParcentage = i === 0 ? 0 : prevWithCumPercentages[i - 1].cumulativePercentageR
const newDatum = {
...datum,
cumulativePercentageR: datum.value + cumulativeParcentage,
}
prevWithCumPercentages.push(newDatum)
return prevWithCumPercentages
}, [])
慕无忌1623718
哆啦的时光机
相关分类