P
P
partizzend2019-07-30 16:22:20
JavaScript
partizzend, 2019-07-30 16:22:20

How to group nested array elements by heading?

There is an array: And another array:
var ind = ["Apple", "Pear", "Banana"];

let arr = [
  [ "Pear",        12,       34,     54,     76,      23,      232    ],
  [ "Apple",      54,       22,     11,     23,      21,      33      ],
  [ "Banana",   54,       65,     11,     43,      66,      75      ],
  [ "Pear",        23,       11,     46,     76,      33,      98      ],
  [ "Apple",      12,       34,     54,     76,      23,      232    ],
  [ "Banana",   54,       22,     11,     23,      21,      33      ],
];

How to concatenate all subarray values ​​in order as they go in ind array to do it like this:
let arr = [
  ["Apple",    [54,12], [22,34], [11,54], [23,76], [21,23], [33,232]],
  ["Pear",      [12,23], [34,11], [54,46], [76,76], [23,33], [232,38]],
  ["Banana", [54,54], [65,22], [11,11], [43,23], [66,21], [75,33 ]]
];

That is, first combine the values ​​​​of arrays into subarrays, into a cat. the first value is Apple, then Pear, then Banana. Like in an array var ind = ["Apple", "Pear", "Banana"];
The result may be as above, it may be as below:
let arr = [
  ,
  ,
  
];

It is highly desirable without things like Spread syntax (...) and Object.values(), since it needs to work at least in the latest ie

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-07-30
@partizzend

ind.map(((data, n) => data[n]).bind(null, arr.reduce((acc, row) => {
  const d = acc[row[0]];
  row.forEach((n, i) => i && (d[i] = d[i] || []).push(n));
  return acc;
}, ind.reduce((acc, n) => (acc[n] = [ n ], acc), {}))))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question