javascript:仅尝试将数组展平 [英] javascript: Trying to flatten array only one level

查看:55
本文介绍了javascript:仅尝试将数组展平的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个将数组展平的函数.我的部分功能正在运行,另一半需要帮助.

I am trying to write a function to flatten an array. I have part of the function working and I need help in the other half.

flatten: function(anyArray, singleLevel) {
  if (singleLevel == true) {
      flatArray = Array.prototype.concat.apply([], anyArray);
      return flatArray;
  }
  flatArray = Array.prototype.concat.apply([], anyArray);
  if (flatArray.length != anyArray.length) {
      flatArray = someObject.array.flatten(flatArray);
  }
  return flatArray;
}

如果我键入

.flatten([[[1],[1,2,3,[4,5],4],[2,3]]], true);

我希望它仅展平一个级别:

I want it to flatten only one level:

[[1],[1,2,3,[4,5],4],[2,3]]

推荐答案

现代JavaScript允许我们使用多种技术轻松处理此问题

Modern JavaScript allows us to handle this very easily using a variety of techniques

使用Array.prototype.flat-

const arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
  
const flatArr =
  arr.flat(1) // 1 is default depth

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]

使用Array.prototype.flatMap-

const arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
  
const flatArr =
  arr.flatMap(x => x)

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]

Array.prototype.concat

const arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
  
const flatArr =
  [].concat(...arr)
  
console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]

JavaScript的旧版本(ECMAScript 5和更低版本)可以使用Function.prototype.apply-

Older version of JavaScript (ECMAScript 5 and below) can use techniques like Function.prototype.apply -

var arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
  
var flatArr =
  Array.prototype.concat.apply([], arr)
  
console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]

使用Array.prototype.reduce-

var arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]

var flatArr =
  arr.reduce((r, a) => r.concat(a), [])

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]

使用原始的for循环-

var arr =
  [ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]

var flatArr =
  []
  
for (var i = 0; i < arr.length; i = i + 1)
  flatArr = flatArr.concat(arr[i])

console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]

这篇关于javascript:仅尝试将数组展平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆