我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
要在一行中展平二维阵列,请执行以下操作:
[[1, 2], [3, 4, 5]].reduce(Function.prototype.apply.bind(Array.prototype.concat))
// => [ 1, 2, 3, 4, 5 ]
其他回答
递归调用deepFlatten函数,这样我们就可以在不使用任何外部助手方法的情况下扩展内部数组。
const innerArr = ['a', 'b'];
const multiDimArr = [[1, 2], 3, 4, [5, 6, innerArr], 9];
const deepFlatten = (arr) => {
const flatList = [];
arr.forEach(item => {
Array.isArray(item)
? flatList.push(...deepFlatten(item)) // recursive call
: flatList.push(item)
});
return flatList;
}
当您的数组中可能有一些非数组元素时,这是一种更一般情况的解决方案。
function flattenArrayOfArrays(a, r){
if(!r){ r = []}
for(var i=0; i<a.length; i++){
if(a[i].constructor == Array){
flattenArrayOfArrays(a[i], r);
}else{
r.push(a[i]);
}
}
return r;
}
这是我的版本。它允许您将复杂的对象展平,可以在更多场景中使用:
输入
var input = {
a: 'asdf',
b: [1,2,3],
c: [[1,2],[3,4]],
d: {subA: [1,2]}
}
Code
功能如下:
function flatten (input, output) {
if (isArray(input)) {
for(var index = 0, length = input.length; index < length; index++){
flatten(input[index], output);
}
}
else if (isObject(input)) {
for(var item in input){
if(input.hasOwnProperty(item)){
flatten(input[item], output);
}
}
}
else {
return output.push(input);
}
};
function isArray(obj) {
return Array.isArray(obj) || obj.toString() === '[object Array]';
}
function isObject(obj) {
return obj === Object(obj);
}
用法
var output = []
flatten(input, output);
输出
[“asdf”,1,2,3,1,2,3,4,1,2]
由于ES2019引入了flat和flatMap,因此任何阵列都可以这样做:
const myArr = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
const myArrFlat= myArr.flat(Infinity);
console.log(myArrFlat); // ["$6", "$12", "$25", ...]
裁判。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
以下是使用堆栈的非递归展平深度的解决方案。
function flatten(input) {
const stack = [...input];
const res = [];
while (stack.length) {
const next = stack.pop();
if (Array.isArray(next)) {
stack.push(...next);
} else {
res.push(next);
}
}
return res.reverse();
}
const arrays = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];
flatten(arrays);