簡體   English   中英

在更改子數組時將子數組復制到另一個數組中?

[英]Copying subarrays into another array while changing them?

所以我試圖將這些子數組復制到另一個數組中並更改它們,以便它們的值在我放入它們時是累積的。為了使它們累積,我使用 map function 並基於我制作的常量變量進行建模。 在嘗試將它們復制到另一個數組中時,我嘗試了 concat、push 和其他方法,但均未成功。

JS

const cumulative = (cumu => val => cumu += val)(0);
var series2 = series.map(cumulative);

            series: [
                [55, 65, 76, 88, 44, 33, 54, 65, 7, 98, 12, 109],
                [52, 25, 26, 82, 24, 23, 34, 65, 47, 59, 12, 19],
                [57, 68, 77, 78, 44, 43, 74, 16, 71, 91, 11, 29]
            ]

下面的這個數組只是為了演示我試圖做的預期效果......

series2: [
    [55, 120, 196... etc...],
    [...],
    [...]
]

猜猜我破解了它。 你的邏輯是錯誤的,你應該使用內部 map:

 series = [ [55, 65, 76, 88, 44, 33, 54, 65, 7, 98, 12, 109], [52, 25, 26, 82, 24, 23, 34, 65, 47, 59, 12, 19], [57, 68, 77, 78, 44, 43, 74, 16, 71, 91, 11, 29] ]; const cumulative = (cumu) => { var val = 0; return cumu.map(c => val += c); }; var series2 = series.map(cumulative); console.log(series2);

我得到這個 output 這就是你要做的:

[
  [55, 120, 196, 284, 328, 361, 415, 480, 487, 585, 597, 706],
  [758, 783, 809, 891, 915, 938, 972, 1037, 1084, 1143, 1155, 1174],
  [1231, 1299, 1376, 1454, 1498, 1541, 1615, 1631, 1702, 1793, 1804, 1833]
]

我認為reduce是以您想要的方式將數組轉換為累積和之一的最佳工具。 使用它來定義轉換單個數組的 function,然后在外部數組上僅map

 const series = [ [55, 65, 76, 88, 44, 33, 54, 65, 7, 98, 12, 109], [52, 25, 26, 82, 24, 23, 34, 65, 47, 59, 12, 19], [57, 68, 77, 78, 44, 43, 74, 16, 71, 91, 11, 29] ]; const makeCumulative = arr => arr.reduce((cums, current) => { const subtotal = cums[cums.length - 1] || 0; return [...cums, subtotal + current]; }, []); const series2 = series.map(makeCumulative); console.log(series2);

使用reduce

 let series = [ [55, 65, 76, 88, 44, 33, 54, 65, 7, 98, 12, 109], [52, 25, 26, 82, 24, 23, 34, 65, 47, 59, 12, 19], [57, 68, 77, 78, 44, 43, 74, 16, 71, 91, 11, 29], ]; console.log(series.map( (ar) => ar.reduce((acc, el) => [...acc, el + (acc[acc.length - 1] || 0)], []) ));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM