I would like to dynamicaly regroup each element with same index of multiple (no precise number) arrays with the same length in a array.
Example :
var arrayOfarray =[
['a','b','c','d','e','f'],
['h','i','j','k','l','m'],
]
/*
expectedResult = [['a','h'],['b','i'],['c','j'],['d','k'],['e','l'],['f','m']]
*/
Thank you
var a = [1, 2, 3]
var b = ['a', 'b', 'c']
var c = a.map(function(e, i) {
return [e, b[i]];
});
console.log(c)
var result = [];
for(var i = 0; i < arrayOfarray.length; i++){
for(var j = 0; j < arrayOfarray[i].length; j++){
result.push([arrayOfarray[i][j], arrayOfarray[(i+1)%2][j]]);
}
}
it's just 2 nested for loops ... nothing fancy
the thing we have to realize is, that the length of the array we want to return is the same as the length of the nested arrays of the array we pass to the function.
and each nested array in the array we want to return has the same length as the main array we pass to the function.
so ists basically like
passedArray.length === returnedArray[i].length //true
passedArray[i].length === returnedArray.length //true
function x(arr) {
const retVal = [];
for (let i = 0, subArr; i < arr[0].length; i++) {
subArr = []
for (let j = 0; j < arr.length; j++) {
subArr.push(arr[j][i])
}
retVal.push(subArr)
}
return retVal
}
const arrayOfarray = [['a', 'b', 'c', 'd', 'e', 'f'], ['h', 'i', 'j', 'k', 'l', 'm']];
console.log(x(arrayOfarray));