【发布时间】:2021-10-13 22:41:16
【问题描述】:
正如我在标题中提到的,我有多个包含一些数据的数组。一些数组具有累积数字,其他数组具有随机数据。我想做的是,
逻辑:if an array is not cumulative, then make it cumulative.
//Randomized arrays are
arrays= [[
'0.029', '0.029', '0.030', '0.030', '0.031', '0.031',
'0.032', '0.032', '0.033', '0.034', '0.034', '0.034',
'0.039', '0.039', '0.001',
'0.001', '0.002', '0.003', '0.003', '0.004', '0.004',
'0.005', '0.006', '0.006', '0.007', '0.007', '0.008',
'0.011', '0.012', '0.012', '0.013', '0.014', '0.014',
'0.015', '0.015', '0.016', '0.017'
],
[
'0.002', '0.002', '0.002', '0.002',
'0.003', '0.003', '0.003', '0.003',
'0.003', '0.004', '0.004', '0.004',
'0.000', '0.000', '0.000', '0.001',
'0.001', '0.001', '0.001', '0.001',
'0.001', '0.001', '0.001', '0.002',
'0.002', '0.002', '0.002', '0.002',
'0.003', '0.003', '0.003'
],
// Cumulative array
[
'0.002', '0.004', '0.006', '0.008',
'0.011', '0.014', '0.017', '0.020',
'0.023', '0.027', '0.031', '0.035',
'0.035', '0.035', '0.035', '0.036',
'0.037', '0.038', '0.039', '0.040',
'0.041', '0.042', '0.043', '0.045',
'0.047', '0.049', '0.051', '0.053',
'0.055', '0.057', '0.059', '0.061',
'0.064', '0.067', '0.070'
]]
我试过这样。
var lastData=[]
for (i in arrays) {
// I thought that if array still includes 0 data inside, than make it cumulative
if (arrays[i].indexOf("0.000") !== -1) {
console.log(i, ' is cumulative'
lastData = arrays[i].map((elem, index) =>
arrays[i].slice(0, index + 1)
.reduce((a, b) =>
(parseFloat(a) + parseFloat(b)).toFixed(3)))
}
}
【问题讨论】:
标签: javascript arrays cumulative-sum