Brixsta
Brixsta

Reputation: 625

Combing multiple Arrays using concat() method

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?

Upvotes: 0

Views: 95

Answers (4)

Taimoor Qureshi
Taimoor Qureshi

Reputation: 630

you can do it that way using array#flat

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

//(6) [1, 4, true, false, "x", "y"]

Upvotes: 9

Luis
Luis

Reputation: 133

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

Upvotes: 0

Lakshya Raj
Lakshya Raj

Reputation: 1775

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.

Upvotes: 0

Mr. Hedgehog
Mr. Hedgehog

Reputation: 2885

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

Upvotes: 3

Related Questions