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?

5
  • 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.) Commented Mar 14, 2021 at 20:47
  • 1
    Duplicate of Merge/flatten an array of arrays. Commented Mar 14, 2021 at 20:52
  • @SebastianSimon: But this question is trying to make the function, not figure out what function to use. Commented Mar 14, 2021 at 20:57
  • @LakshyaRaj There are 83 answers on this question; some of them also use for loops. Commented Mar 14, 2021 at 21:00
  • @SebastianSimon: Oh, I understand. Going to flag as duplicate. Commented Mar 14, 2021 at 21:18

4 Answers 4

9

you can do it that way using array#flat

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

//(6) [1, 4, true, false, "x", "y"]
Sign up to request clarification or add additional context in comments.

Comments

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();
}

Comments

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.

Comments

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();

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.