简体   繁体   中英

How to group elements of nested arrays?

There is an array:

var ind = ["Apple", "Pear", "Banana"];

And another array:

var arr = [
  ["Apple", "Banana", "Pear", "Pear", "Apple", "Apple", "Banana"],
  [ 11,      12,       34,     54,     76,      23,      232    ],
  [ 33,      54,       22,     11,     23,      21,      33     ]
];

How to combine all the values of the subarrays in order, as they go in the array ind, to make it like this:

var arr = [
  [ "Apple",      "Pear",   "Banana"  ],
  [  [11, 76, 23], [34, 54], [12, 232]],
  [  [33, 23, 21], [22, 11], [54, 33] ]
];

You could do this with reduce and forEach methods to create new array and add sub-arrays based on indexOf current element from the first row and index of the same element in ind array.

 var ind = ["Apple", "Pear", "Banana"]; var arr = [ ["Apple", "Banana", "Pear", "Pear", "Apple", "Apple", "Banana"], [11, 12, 34, 54, 76, 23, 232], [33, 54, 22, 11, 23, 21, 33] ]; const first = arr[0]; const result = arr.slice(1).reduce((r, e, i) => { const a = r[i + 1] = []; e.forEach((el, j) => { const index = ind.indexOf(first[j]) if (!a[index]) a[index] = [el]; else a[index].push(el) }) return r; }, [ind]) console.log(result) 

You could take an array as helper for getting the right index and reduce the array by taking the index and collect the values to the index.

 var columns = ["Apple", "Pear", "Banana"], data = [["Apple", "Banana", "Pear", "Pear", "Apple", "Apple", "Banana"], [11, 12, 34, 54, 76, 23, 232], [33, 54, 22, 11, 23, 21, 33]], indices = data[0].map(v => columns.indexOf(v)), result = [columns, ...data.slice(1).map(a => a.reduce((r, v, i) => { (r[indices[i]] = r[indices[i]] || []).push(v); return r; }, []))]; console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You can reduce to merge the values into one depending on the index of head

 var ind = ["Apple", "Pear", "Banana"]; var [head, ...rest] = [ ["Apple", "Banana", "Pear", "Pear", "Apple", "Apple", "Banana"], [ 11, 12, 34, 54, 76, 23, 232 ], [ 33, 54, 22, 11, 23, 21, 33 ] ]; let out = [ind, ...rest.map(row => Object.values(row.reduce((acc, curr, i) => (acc[head[i]].push(curr), acc), ind.reduce((acc, curr) => (acc[curr] = [], acc), {}))))]; console.log(out) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM