最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Flatten an array with forEach - Stack Overflow

programmeradmin4浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 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

.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) 

发布评论

评论列表(0)

  1. 暂无评论