DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Nic
Nic

Posted on

Separate array of arrays into arrays

Let's say you have an array of arrays like this:
[ ['one', 1], ['two', 2], ['three', 3] ]
and what you want are two arrays that are:
['one', 'two', 'three']
[1, 2, 3]

How do you do that?

Array looping - maps and filters

All you have to do is to loop through the outside array and then the inside array:

const arrayOne = outerArray.map(innerArray => {
  return innerArray.filter((innerArrayItem, index) => index === 0);
});

const array2 = outerArray.map(innerArray => {
  return innerArray.filter((innerArrayItem, index) => index === 1);
});
Enter fullscreen mode Exit fullscreen mode

What we're doing is looping through the outside array using a map. Then for each of the inner arrays within it, we are picking out the item with the relevant index. So for arrayOne we want all of the numbers as strings, which are the first elements in each array.

Array looping - for loops

If you're not familiar with map and filter you can use two for loops:

let arrayOne = []
let array2 = []
for (let i = 0; i < outerArray.length; i++) {
  for (let j = 0; j < outerArray[i].length; j++) {
    if (j === 0) {
      arrayOne.push(outerArray[i][j]);
    }
    if (j === 1) {
      array2.push(outerArray[i][j]);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The advantage of this is that you can push to both arrays at the same time. But the first example is easier to scale up - you can easily put it in a function if your inner array has three elements that you want to pull out into three arrays.

Top comments (0)

🌚 Life is too short to browse without dark mode