I have a multidimensional array, which I don't know its size, what I do know is that each child will have the same length and same structure.
I need to concat the inner arrays of the first child with the inner arrays of its siblings so all the children same index inner arrays are in one array.
(If someone wants to phrase it a little bit better, or improve the title be my guest)
Example:
let arrays = [
//1
[[1, 2], [3, 4], [5, 6]],
//2
[[10, 20], [30, 40], [50, 60]],
//3
[[100, 200], [300, 400], [500, 600]],
//N
[[10000, 20000], [30000, 40000], [50000, 60000]],
];
Expected result:
[
[1, 2, 10, 20, 100, 200, 10000, 20000],
[3, 4, 30, 40, 300, 400, 30000, 40000],
[5, 6, 50, 60, 500, 600, 50000, 60000]
]
Here is what I'm currently doing, which is working, but it's an overkill.
/**
* Helper function
* Will return all the values at ${index} of each array in ${arrays}
* Example: index(1, [[1,2], [3,4]]); //[2, 4]
*/
function index(index, arrays){
let results = [];
for(let i = 0, len = arrays.length; i < len; i++)
results.push(arrays[i][index]);
return results;
}
let first = arrays.shift();
let output = first.map((item, i) => item.concat( ...index(i, arrays) ))
I'm looking for a more efficient way to do this, since it's running in a node server and also a more clever way (which doesn't have to be more efficient).
Note: I'm using node v7.8.0 so ES6 can be used.
UPDATE:
The spread operator is significantly slower than apply
So my code is much faster this way:
return first.map((item, i) => [].concat.apply(item, index(i, clone) ));
JSPERF:
I tested all the answers in this jsperf and @ibrahimMahrir way is clearly the fastest.
/**
* Will return all the values at ${index} of each array in ${arrays}
* Example: index(1, [[1,2], [3,4]]); //[2, 4]
*/
function index(index, arrays){
let results = [];
for(let i = 0, len = arrays.length; i < len; i++)
results.push(arrays[i][index]);
return results;
}
let arrays = [
//1
[[1, 2], [3, 4], [5, 6]],
//2
[[10, 20], [30, 40], [50, 60]],
//3
[[100, 200], [300, 400], [500, 600]],
//N
[[10000, 20000], [30000, 40000], [50000, 60000]],
];
let first = arrays.shift();
let output = first.map((item, i) => item.concat( ...index(i, arrays) ));
console.log(output);