首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不使用.flat()展平数组;

不使用.flat()展平数组;
EN

Stack Overflow用户
提问于 2020-07-06 02:40:55
回答 8查看 1.2K关注 0票数 4

如何在不使用flat()的情况下展平数组。1级?

到目前为止,我有这个

代码语言:javascript
复制
function flatten(array) {
  let flattened = [];
  for (let i = 0; i < array.length; i++) {
    const current = array[i];
    for (let j = 0; i < current.length; j++) {
      flattened.push(current[j])
    }
  }
  return flattened
}

console.log(flatten([['foo', 'bar'], ['baz', 'qux']]));
// -> ["foo", "bar", "baz", "qux"]
flatten([[1], [2], 3, 4, [5]]);
// -> [1, 2, 3, 4, 5]
flatten([false, [true, [false]], [true]]);
// -> [false, true, [false], true]
flatten([]);
// -> []

它粉碎了我的记忆

EN

回答 8

Stack Overflow用户

发布于 2020-07-06 02:45:10

我希望这能帮到你

代码语言:javascript
复制
var twoDimension = [[1], [2], 3, 4, [5]];

var plano = twoDimension.reduce((acc, el) => acc.concat(el), []);

console.log(plano);

票数 5
EN

Stack Overflow用户

发布于 2020-07-06 02:44:15

您可以使用Array.reducespread syntax

代码语言:javascript
复制
function flatten(array) {
  return array.reduce(
    (accumulator, item) => {
      // if `item` is an `array`,
      // use the `spread syntax` to 
      // append items of the array into 
      // the `accumulator` array
      if (Array.isArray(item)) {
        return [...accumulator, ...item];
      }
      // otherwise, return items in the 
      // accumulator plus the new item
      return [...accumulator, item];
    }
  , []); // initial value of `accumulator`
}

console.log(flatten([['foo', 'bar'], ['baz', 'qux']]));
// -> ["foo", "bar", "baz", "qux"]
console.log(flatten([[1], [2], 3, 4, [5]]));
// -> [1, 2, 3, 4, 5]
console.log(flatten([false, [true, [false]], [true]]));
// -> [false, true, [false], true]
console.log(flatten([]));
// -> []

参考文献:

票数 3
EN

Stack Overflow用户

发布于 2020-07-06 02:47:43

您可以使用javascript的reducer作为flat()的替代。

代码语言:javascript
复制
const arr = [1, 2, [3, 4]];

arr.reduce((acc, val) => acc.concat(val), []);
// [1, 2, 3, 4]

或者您可以使用分解语法

代码语言:javascript
复制
const flattened = arr => [].concat(...arr);

有关更多详细信息,请访问Mozilla MDN

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62744911

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档