This may be a very basic question, but I am not very familiar with JS and trying to teach myself on the fly for a PCR project at work and would love some help.
I have a Javascript array formatted as
//[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],
There is a total of 16 wells and 35 cycles per well. I need to pivot or reformat the data so that I can correctly graph it using google core charts. The chart requires the data be input as
//[cycle, Result(well1), Result(well2), etc...]//
[1, -4778, -3655, etc..]
[2, -4066, -2948, etc..]
I have an attempt at doing this on a fiddle here. Please excuse the messy fiddle, I've been messing around in it trying to figure stuff out. Thank you in advance!
We can do this by reduce
ing the array and gathering the results per cycle together in a cycle-keyed, results-array-valued object, and then combining the keys and values into a single object when they're all gathered:
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}
While I find that style code very clean, it is less efficient than we might prefer. Either of these two stylistic variants of one another would do the same job more efficiently, although to my mind less elegantly:
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])
or
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])