[英]How does one consolidate multi-dimensional arrays?
I am trying to get one array with a complete string:我正在尝试使用完整的字符串获取一个数组:
['...'] ['……']
Given:鉴于:
Array1 = ['...', ['...'], ['...', 2, 'x']] Array1 = ['...', ['...'], ['...', 2, 'x']]
This should handle any size array*这应该处理任何大小的数组*
Define a function, zooInventory
, that accepts a multi-dimensional array of animal facts.定义一个函数
zooInventory
,它接受动物事实的多维数组。
zooInventory
should return a new, flat array. zooInventory
应该返回一个新的平面数组。 Each element in the new array should be a sentence about each of the animals in the zoo.新数组中的每个元素都应该是一个关于动物园中每一种动物的句子。
What I have currently:我目前拥有的:
const zooInventory = array => {
let finalArray = [];
for (let i = 0; i < array.length; i++) {
let currentElement = array[i];
if (!(Array.isArray(currentElement))) {
finalArray.push(currentElement);
} else {
zooInventory(currentElement);
// I thought I could push the currentElement back to beginning to handle additional arrays
}
}
return finalArray;
}
Where my heads at:我的头在:
I thought I could get away with having it push(...array) in the else statement.我以为我可以在 else 语句中使用它 push(...array) 。
My batman belt contains beginner methods... slice, splice, spread.我的蝙蝠侠腰带包含初学者方法......切片,拼接,传播。
What method would be best practice?什么方法是最佳实践?
Simply use the .flat()
method as shown in the snippet below.只需使用
.flat()
方法,如下面的代码片段所示。
More information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat更多信息: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
let arrayOne = ['...', ['...'], ['...', 2, 'x']]; console.log(arrayOne.flat());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.