-1

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

Nicoprrt
  • 15
  • 2
  • Does this answer your question? [Javascript equivalent of Python's zip function](https://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-function) – pilchard Jul 21 '22 at 17:21
  • also [How do I zip two arrays in JavaScript?](https://stackoverflow.com/questions/22015684/how-do-i-zip-two-arrays-in-javascript) – pilchard Jul 21 '22 at 17:22
  • also, SO is not a coding service. Show what you have tried and where you are stuck. See [How to Ask](https://stackoverflow.com/questions/how-to-ask), and provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) of your attempt. – pilchard Jul 21 '22 at 17:24

2 Answers2

0
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]]);
    }
} 
  • 1
    Please read [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). While this code block may answer the OP's question, this answer would be much more useful if you explain how this code is different from the code in the question, what you've changed, why you've changed it and why that solves the problem without introducing others. – Saeed Zhiany Jul 22 '22 at 06:15
0

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));
pilchard
  • 12,414
  • 5
  • 11
  • 23
Lord-JulianXLII
  • 1,031
  • 1
  • 6
  • 16