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?
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?
Share Improve this question asked Apr 1, 2018 at 7:09 chamcham 10.9k10 gold badges54 silver badges70 bronze badges3 Answers
Reset to default 6You 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
.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 pleting 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);
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)