我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
适用于所有数据类型的递归版本
/*jshint esversion: 6 */
// nested array for testing
let nestedArray = ["firstlevel", 32, "alsofirst", ["secondlevel", 456,"thirdlevel", ["theinnerinner", 345, {firstName: "Donald", lastName: "Duck"}, "lastinner"]]];
// wrapper function to protect inner variable tempArray from global scope;
function flattenArray(arr) {
let tempArray = [];
function flatten(arr) {
arr.forEach(function(element) {
Array.isArray(element) ? flatten(element) : tempArray.push(element); // ternary check that calls flatten() again if element is an array, hereby making flatten() recursive.
});
}
// calling the inner flatten function, and then returning the temporary array
flatten(arr);
return tempArray;
}
// example usage:
let flatArray = flattenArray(nestedArray);
其他回答
let arr = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"], ["$0"], ["$15"],["$3"], ["$75"], ["$5"], ["$100"], ["$7"], ["$3"], ["$75"], ["$5"]];
arr = arr.reduce((a, b) => a.concat(b)); // flattened
更简单和直接的方法;可选择深压平;
const flatReduce = (arr, deep) => {
return arr.reduce((acc, cur) => {
return acc.concat(Array.isArray(cur) && deep ? flatReduce(cur, deep) : cur);
}, []);
};
console.log(flatReduce([1, 2, [3], [4, [5]]], false)); // => 1,2,3,4,[5]
console.log(flatReduce([1, 2, [3], [4, [5, [6, 7, 8]]]], true)); // => 1,2,3,4,5,6,7,8
递归调用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;
}
我写的简单的flatten util
const flatten = (arr, result = []) => {
if (!Array.isArray(arr)){
return [...result, arr];
}
arr.forEach((a) => {
result = flatten(a, result)
})
return result
}
console.log(flatten([1,[2,3], [4,[5,6,[7,8]]]])) // [ 1, 2, 3, 4, 5, 6, 7, 8 ]
以下代码将压平深度嵌套的数组:
/**
* [Function to flatten deeply nested array]
* @param {[type]} arr [The array to be flattened]
* @param {[type]} flattenedArr [The flattened array]
* @return {[type]} [The flattened array]
*/
function flattenDeepArray(arr, flattenedArr) {
let length = arr.length;
for(let i = 0; i < length; i++) {
if(Array.isArray(arr[i])) {
flattenDeepArray(arr[i], flattenedArr);
} else {
flattenedArr.push(arr[i]);
}
}
return flattenedArr;
}
let arr = [1, 2, [3, 4, 5], [6, 7]];
console.log(arr, '=>', flattenDeepArray(arr, [])); // [ 1, 2, [ 3, 4, 5 ], [ 6, 7 ] ] '=>' [ 1, 2, 3, 4, 5, 6, 7 ]
arr = [1, 2, [3, 4], [5, 6, [7, 8, [9, 10]]]];
console.log(arr, '=>', flattenDeepArray(arr, [])); // [ 1, 2, [ 3, 4 ], [ 5, 6, [ 7, 8, [Object] ] ] ] '=>' [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]