Reputation: 625
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
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
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
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
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