用于绘图的数据透视表

Pivot Data for Graphing

这可能是一个非常基本的问题,但我对 JS 不是很熟悉,正在努力自学工作中的 PCR 项目,希望得到一些帮助。

我有一个 Javascript 数组,格式为

//[well, cycle, result]//
[1, 1, -4778],
[1, 2, -4066],
[1, 3, -3647],
[1, 4, -3111],
[1, 5, -2861],
[2, 1, -3655],
[2, 2, -2948],
[2, 3, -2665],
[2, 4, -2289],
[2, 5, -2126],

一共16个孔,每孔35个循环。我需要对数据进行透视或重新格式化,以便我可以使用 google 核心图表正确地绘制它。图表要求数据输入为

//[cycle, Result(well1), Result(well2), etc...]//
[1, -4778, -3655, etc..]
[2, -4066, -2948, etc..]

我尝试在 fiddle here 上执行此操作。请原谅乱七八糟的fiddle,我一直在里面乱搞,试图弄清楚一些东西。提前致谢!

我们可以通过 reduceing 数组并将每个循环的结果收集到一个循环键控、结果数组值对象中,然后将键和值组合到一个对象中来做到这一点他们都聚集了:

const pivot = (input) => Object .entries (input .reduce (
  (a, [well, cycle, result]) => ({...a, [cycle]: [...(a[cycle] || []), result]}),
  {}
)) .map (([cycle, results]) => [Number (cycle), ...results])

const input = [[1, 1, -4778], [1, 2, -4066], [1, 3, -3647], [1, 4, -3111], [1, 5, -2861], [2, 1, -3655], [2, 2, -2948], [2, 3, -2665], [2, 4, -2289], [2, 5, -2126]]

console .log (pivot (input))
.as-console-wrapper {max-height: 100% !important; top: 0}

虽然我发现该样式代码非常简洁,但 less efficient 超出了我们的预期。这两种文体变体中的任何一种都会更有效地完成相同的工作,尽管在我看来不太优雅:

const pivot = (input) => Object .entries (input .reduce (
  (a, [well, cycle, result]) => 
    ((a [cycle] = a [cycle] || []), (a [cycle] .push (result)), a),
  {}
)) .map (([cycle, results]) => [Number (cycle), ...results])

const pivot = (input) => Object .entries (input .reduce (
  (a, [well, cycle, result]) => {
    a [cycle] = a [cycle] || []
    a [cycle] .push (result)
    return a
  },
  {}
)) .map (([cycle, results]) => [Number(cycle), ...results])