我有一个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);
其他回答
我建议使用节省空间的发电机功能:
函数*展平(arr){如果(!Array.isArray(arr))产生arr;否则为(设arr的el)屈服*展平(el);}//示例:console.log(…flatten([1,[2,[3,[4]]]));//1 2 3 4
如果需要,请创建一个展平值数组,如下所示:
let flattened = [...flatten([1,[2,[3,[4]]]])]; // [1, 2, 3, 4]
如果只有一个字符串元素的数组:
[["$6"], ["$12"], ["$25"], ["$25"]].join(',').split(',');
将完成这项工作。与您的代码示例具体匹配的Bt。
如果你使用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)
您可以使用“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"]
const common = arr.reduce((a, b) => [...a, ...b], [])