0
function joinArrayOfArrays(arr) {
  var startingArray = arr[0];
  var newArray = [];

 for(var i=0; i<arr.length; i++) {
   newArray = startingArray.concat(arr[i]);
  
 }

  return newArray;
}

var output = joinArrayOfArrays([[1, 4], [true, false], ['x', 'y']]);
console.log(output); // --> [1, 4, true, false, 'x'

I want to loop through a for loop and using the concat() method and compile the results in single array. I cannot figure it out Any help?

Brixsta
  • 605
  • 12
  • 24
  • 2
    you've just got your variables mixed up. `newArray = startingArray.concat(arr[i])` should be `newArray = newArray.concat(arr[i])` (And you of course don't need `startingArray` at all, it's handled in the first iteration of the loop.) – Robin Zigmond Mar 14 '21 at 20:47
  • 1
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+flatten+array) of [Merge/flatten an array of arrays](https://stackoverflow.com/q/10865025/4642212). – Sebastian Simon Mar 14 '21 at 20:52
  • @SebastianSimon: But this question is trying to make the function, not figure out what function to use. – Lakshya Raj Mar 14 '21 at 20:57
  • @LakshyaRaj There are 83 answers on this question; some of them also use `for` loops. – Sebastian Simon Mar 14 '21 at 21:00
  • @SebastianSimon: Oh, I understand. Going to flag as duplicate. – Lakshya Raj Mar 14 '21 at 21:18

4 Answers4

9

you can do it that way using array#flat

[[1, 4], [true, false], ['x', 'y']].flat()

//(6) [1, 4, true, false, "x", "y"]
Taimoor Qureshi
  • 620
  • 4
  • 14
3

Option one is to destructure your array into concat, since concat can accept multiple arguments:

function joinArrayOfArrays(arr) {
  return [].concat(...arr);
}

Option two would be to flatten your array:

function joinArrayOfArrays(arr) {
  return arr.flat();
}
Mr. Hedgehog
  • 2,644
  • 1
  • 14
  • 18
0

The problem is that you are reassigning newArray each time so that won't work. Just remove startingArray completely and it will work:

function joinArrayOfArrays(arr) {
  var newArray = [];

 for(var i=0; i<arr.length; i++) {
   newArray = newArray.concat(arr[i]);
  
 }

  return newArray;
}

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

Of course, you could use Array.flat() like mentioned in another answer, or also [].concat(...arr) from another answer too.

Lakshya Raj
  • 1,669
  • 3
  • 10
  • 34
0

Modifying the code as little as possible a solution that works well is:

function joinArrayOfArrays(arr) {
  var newArray = [];

 for(var i=0; i<arr.length; i++) {
   console.log(arr[i])
   newArray = newArray.concat(arr[i]);
  
 }

  return newArray;
}

var output = joinArrayOfArrays([[1, 4], [true, false], ['x', 'y']]);
console.log(output);//->[1, 4, true, false, "x", "y"]

Effectively another way is to use arr.flat();

Luis
  • 133
  • 6