使用es6从数组数组创建滚动数组

时间:2019-02-09 19:41:46

标签: javascript ecmascript-6

我有一个类似的数据集。

this.data = [[opens, opens, opens, etc],
  [closes, closes, closes, etc],
  [highs, highs, highs, etc],
  [lows, lows, lows, etc]]

我有一个函数,它捕获每个数组的第一项并返回单个数组,如

[opens, closes, highs, lows]

我需要功能来实际创建一个滚动窗口,所以就像

[opens, closes, highs, lows],
[opens, closes, highs, lows], 
[opens, closes, highs, lows],
[opens, closes, highs, lows], 
[opens, closes, highs, lows],

对于这个例子,我要最后四个和当前一个。

该函数正在使用reduce。我需要用哪种语法替换reduce?

const candle = this.data.reduce(
    (array, item) => [...array, item[index]],
    []
  );

3 个答案:

答案 0 :(得分:1)

您可以先旋转数据,然后获取一个子集。

var data = [['opens0', 'opens1', 'opens2', 'opens3', 'opens4', 'opens5'], ['closes0', 'closes1', 'closes2', 'closes3', 'closes4', 'closes5'], ['highs0', 'highs1', 'highs2', 'highs3', 'highs4', 'highs5'], ['lows0', 'lows1', 'lows2', 'lows3', 'lows4', 'lows5']],
    rotated = data.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []);
    
console.log(rotated);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

如果您仍然想使用reduce(),也许可以这样做:

const data = [
  ["opens", "opens", "opens"],
  ["closes", "closes", "closes"],
  ["highs", "highs", "highs"],
  ["lows", "lows", "lows"]
];

let res = data.reduce((acc, list, idx, arr) =>
{
    if (idx >= list.length)
        return acc;

    return [...acc, arr.map(x => x[idx])];
}, []);

console.log(res);

答案 2 :(得分:0)

因为想要一个 nested 数组结果,所以需要首先遍历子数组,而不是遍历外部.data数组。我会使用两个.map

const data = [['opens', 'opens', 'opens'],
  ['closes', 'closes', 'closes'],
  ['highs', 'highs', 'highs'],
  ['lows', 'lows', 'lows']];
const candles = data[0].map((_, i) => data.map(subarr => subarr[i]));
console.log(candles);