0

I have an array of arrays of different lengths. So for instance in my test below I start with my vidArray containing 4 arrays (their length is respectively 16, 38, 49, 49). I'd like to populate a newArray with the first value of each of the 4 arrays, then the second value of each, then the third and so on.

What I'm trying is:

      // populate newArray
      var newArray = []
      for(let i=0; i < vidArray.length; i++){
        let ar = vidArray[i]
        for(let j=i; j < (i+1); j++){
          newArray.push(ar[j])
        }
      }

      console.log("newArray "+newArray)

but it seems to wrongly take the [0] from the first array, the [1] from the second array, the [3] from the third array and so on

3
  • What will you do when there is no more items in first array, but exists in second? null/terminate? Commented Dec 27, 2020 at 23:22
  • Ideally i'd stop fetching that array's items Commented Dec 27, 2020 at 23:25
  • So you just want to go until the end of the shortest subarray has been reached? Commented Dec 27, 2020 at 23:26

2 Answers 2

1

You can figure out the maximum length of the subarrays, then iterate over that length, pushing the corresponding values from each subarray into the new array as you go, skipping any that don't exist:

const vidArray = [
  [1, 2, 3, 4, 5],
  [11, 12, 13, 14],
  [21, 22, 23],
  [31, 32, 33, 34, 35, 36]
];

let newArray = [];
const maxLength = Math.max(...vidArray.map(a => a.length));

for (let i = 0; i < maxLength; i++) {
  vidArray.forEach(a => {
    if (a[i]) newArray.push(a[i]);
  });
}

console.log(newArray);

Sign up to request clarification or add additional context in comments.

2 Comments

It works thank you! node suggested me to declare "i" so i did: for (let i = 0; i..etc
@m4tt sorry, that let should be there. I've updated the answer.
0

Here is one potential method that uses a combination of reduce and forEach.

const vidArray = [
  ["a1", "a2", "a3", "a4"],
  ["b1", "b2"],
  ["c1", "c2", "c3", "c4"],
  ["d1", "d2", "d3"]
]

const newArr = vidArray.reduce((acc, arr) => {
  arr.forEach((el, i) => {
    if (!acc[i]) acc[i] = [];
    acc[i].push(el);
  });
  return acc;
}, []);

console.log(newArr);

// If you need the output as one singular array:
console.log(newArr.flat());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.