我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
使用排列运算符:
常量输入=[[“$6”],[“$12”],【“$25”】,[“$25“],【”$18“】,【”$22“】,[”$10“]];常量输出=[].contat(…输入);console.log(输出);//-->["$6", "$12", "$25", "$25", "$18", "$22", "$10"]
其他回答
您可以使用“join()”和“split()”:
设arrs=[["$6"],["$12"],["$25"],["$25"],["$18"],["$22"],["$10"]];让newArr=arrs.join(“,”).split(“,“);console.log(newArr);//["$6", "$12", "$25", "$25", "$18", "$22", "$10"]
此外,还可以使用“toString()”和“split()”:
设arrs=[["$6"],["$12"],["$25"],["$25"],["$18"],["$22"],["$10"]];让newArr=arrs.toString().split(“,”);console.log(newArr);//["$6", "$12", "$25", "$25", "$18", "$22", "$10"]
然而,如果字符串包含逗号,上述两种方式都不能正常工作:
“join()”和“split()”:
设arrs=[["$,6"],["$,12"],["$2,5"],["$2,5"],[",$18"],["$22,"],["$,1,0"]];让newArr=arrs.join(“,”).split(“,“);console.log(newArr);// ["$", "6", "$", "12", "$2", "5", "$2", "5", "", "$18", "$22", "", "$", "1", "0"]
“toString()”和“split()”:
设arrs=[["$,6"],["$,12"],["$2,5"],["$2,5"],[",$18"],["$22,"],["$,1,0"]];让newArr=arrs.toString().split(“,”);console.log(newArr);// ["$", "6", "$", "12", "$2", "5", "$2", "5", "", "$18", "$22", "", "$", "1", "0"]
如果你使用lodash,你可以使用它的flatten方法:https://lodash.com/docs/4.17.14#flatten
lodash的优点是它还具有使数组变平的方法:
i) 递归地:https://lodash.com/docs/4.17.14#flattenDeep
ii)多达n层嵌套:https://lodash.com/docs/4.17.14#flattenDepth
例如
const _ = require("lodash");
const pancake = _.flatten(array)
有一个新的本地方法叫做flat,可以准确地执行此操作。
(截至2019年底,flat现已发布在ECMA 2019标准中,并且core-js@3(babel的库)将其包含在他们的polyfill库中)
const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]
const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]
// Flatten 2 levels deep
const arr3 = [2, 2, 5, [5, [5, [6]], 7]];
arr3.flat(2);
// [2, 2, 5, 5, 5, [6], 7];
// Flatten all levels
const arr4 = [2, 2, 5, [5, [5, [6]], 7]];
arr4.flat(Infinity);
// [2, 2, 5, 5, 5, 6, 7];
有一个令人困惑的隐藏方法,它在不改变原始数组的情况下构造一个新数组:
var oldArray=[[1],[2,3],[4];var newArray=Array.prototype.contat.apply([],oldArray);console.log(newArray);//[ 1, 2, 3, 4 ]
以下代码将压平深度嵌套的数组:
/**
* [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 ]