Search code examples
javascriptarrayspushnested-loopsconcatenation

JavaScript - Join arrays of an array with concat method instead of push method


I have a problem that asks me to join arrays of an array and return a single array in the form of [ array[0][0], array[0][1], array[1][0], array[1][1], etc. ]. I solved it using the push method in nested for-loops, but the prompt says that I should be familiar with the concat method. I know the concat method syntax and how it works, but I can't figure out how to use it to do what the prompt asks for.

Here's my solution using the push method:

function joinArrayOfArrays(arr) {
  var joined = [];
  for (var i = 0; i < arr.length; i++) {
    for (var k = 0; k < arr[i].length; k++) {
      joined.push(arr[i][k]);
    }
  } 
  return joined;
}

joinArrayOfArrays([[1, 4], [true, false], ['x', 'y']]);

// => [ 1, 4, true, false, 'x', 'y' ]

How would I return the same output using the concat method?


Solution

  • If you want to use concatenation, you wouldn't need the second loop, you can just concatenate each sub array within a single loop. One thing to remember is that concat doesn't modify exist array but returns a new one:

    function joinArrayOfArrays(arr) {
      var joined = [];
      for (var i = 0; i < arr.length; i++) {
        joined = joined.concat(arr[i]) // concat sub array
      } 
      return joined;
    }
    
    console.log(
      joinArrayOfArrays([[1, 4], [true, false], ['x', 'y']])
    );

    You can also use a spread in a similar manner:

    function joinArrayOfArrays(arr) {
      var joined = [];
      for (var i = 0; i < arr.length; i++) {
        joined = [...joined, ...arr[i]] // spread
      } 
      return joined;
    }
    
    console.log(
      joinArrayOfArrays([[1, 4], [true, false], ['x', 'y']])
    );

    Using reduce, as suggested by J. Guilherme, is a more elegant way to do this.