Home > Software engineering >  How to dynamicaly regroup each element of multiple arrays with same length
How to dynamicaly regroup each element of multiple arrays with same length

Time:07-22

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

CodePudding user response:

it's just 2 nested for loops ... nothing fancy

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
}

CodePudding user response:

var a = [1, 2, 3]
var b = ['a', 'b', 'c']

var c = a.map(function(e, i) {
  return [e, b[i]];
});

console.log(c)

CodePudding user response:

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]]);
    }
} 
  • Related