我有一个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 = [1, [2, 3, [4, 5, [6, 7], [8, 9, 10, 11, 12]]]];
function flattenList(nestedArr) {
let newFlattenList = [];
const handleFlat = (array) => {
let count = 0;
while (count < array.length) {
let item = array[count];
if (Array.isArray(item)) {
handleFlat(item);
} else {
newFlattenList.push(item);
}
count++;
}
};
handleFlat(nestedArr);
return newFlattenList;
}`enter code here`
console.log(flattenList(arr));
CodeSandBox链接
ES2019年
ES2019引入了Array.protocol.flat()方法,您可以使用它来展平阵列。它与大多数环境兼容,尽管它仅在Node.js版本11开始提供,而在Internet Explorer中根本不提供。
常量数组=[["$6"],["$12"],["$25"],["$25"],["$18"],["$22"],["$10"]];const merge3=arrays.flat(1)//指定嵌套数组结构应展平的深度级别。默认值为1。console.log(合并3);
较旧的浏览器
对于较旧的浏览器,可以使用Array.prototype.cocat合并数组:
var数组=[["$6"],["$12"],["$25"],["$25"],["$18"],["$22"],["$10"]];var merged=[].contat.apply([],数组);console.log(合并);
使用concat的apply方法将只将第二个参数作为数组,因此最后一行与此相同:
var merged = [].concat(["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]);
我知道这有点粗糙,但我所知道的扁平化字符串数组(任何深度!)(没有逗号!)的唯一简洁方法是将数组转换为字符串,然后用逗号分割字符串:
var myArray =[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"], ["$0"], ["$15"],["$3"], ["$75"], ["$5"], ["$100"], ["$7"], ["$3"], ["$75"], ["$5"]];
var myFlatArray = myArray.toString().split(',');
myFlatArray;
// ["$6", "$12", "$25", "$25", "$18", "$22", "$10", "$0", "$15", "$3", "$75", "$5", "$100", "$7", "$3", "$75", "$5"]
这应该适用于任何深度的仅包含字符串和数字(整数和浮点)的嵌套数组,但需要注意的是,数字将在过程中转换为字符串。这可以通过一点映射来解决:
var myArray =[[[1,2],[3,4]],[[5,6],[7,8]],[[9,0]]];
var myFlatArray = myArray.toString().split(',').map(function(e) { return parseInt(e); });
myFlatArray;
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
我提出了两个没有递归的简短解决方案。从计算复杂性的角度来看,它们不是最优的,但在一般情况下工作良好:
let a = [1, [2, 3], [[4], 5, 6], 7, 8, [9, [[10]]]];
// Solution #1
while (a.find(x => Array.isArray(x)))
a = a.reduce((x, y) => x.concat(y), []);
// Solution #2
let i = a.findIndex(x => Array.isArray(x));
while (i > -1)
{
a.splice(i, 1, ...a[i]);
i = a.findIndex(x => Array.isArray(x));
}
深度扁平化和面向对象怎么样?
[23, [34, 454], 12, 34].flatten();
// --> [23,34, 454, 12, 34]
[23, [34, 454,[66,55]], 12, 34].flatten();
// --> [23, 34, 454, [66,55], 12, 34]
深压平:
[23, [34, 454,[66,55]], 12, 34].flatten(true);
// --> [23, 34, 454, 66, 55, 12, 34]
DEMO
CDN
如果所有数组元素都是Integer、Float,。。。或/和字符串,所以只需执行以下操作:
var myarr=[1,[7,[9.2]],[3],90];
eval('myarr=['+myarr.toString()+']');
print(myarr);
// [1, 7, 9.2, 3, 90]
DEMO