2

After checking out this post on flattening arrays, I noticed that no one had used the array method forEach. I gave it a try and failed, only receiving back an empty array:

let arrays = [[1, 2, 3], [4, 5], [6]];
let result = [];

arrays.forEach( (element) => {
    result.concat(element)
})

console.log(result) //[]

Where did I go wrong?

cham
  • 8,666
  • 9
  • 48
  • 69

3 Answers3

6

You have to result = result.concat(element)

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

let arrays = [[1, 2, 3], [4, 5], [6]];
let result = [];

arrays.forEach((element) => {
  result = result.concat(element)
})

console.log(result) //[]

Doc: concat

Eddie
  • 26,593
  • 6
  • 36
  • 58
3

.concat() always returns a new array. It doesn't modify arrays on which it is operating.

You are supposing that .concat() will save result in its operand after completing its opeartion. However it is not the case. You need to save result explicitly after .concat():

result = result.concat(element);

Demo:

let arrays = [[1, 2, 3], [4, 5], [6]];
let result = [];

arrays.forEach((element) => {
  result = result.concat(element)
});

console.log(result);

You can also use spread syntax instead of .forEach() to flatten array.

let result = [].concat(...arrays);

Demo:

let arrays = [[1, 2, 3], [4, 5], [6]];
let result = [].concat(...arrays);

console.log(result);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
2

concat returns a new array and hence you need to assign it to result like result = result.concat(element)

let arrays = [[1, 2, 3], [4, 5], [6]];
let result = [];

arrays.forEach( (element) => {
    result = result.concat(element)
})

console.log(result) 
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400