我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
只是为了增加伟大的解决方案。我用递归来解决这个问题。
const flattenArray = () => {
let result = [];
return function flatten(arr) {
for (let i = 0; i < arr.length; i++) {
if (!Array.isArray(arr[i])) {
result.push(arr[i]);
} else {
flatten(arr[i])
}
}
return result;
}
}
测试结果:https://codepen.io/ashermike/pen/mKZrWK
其他回答
我建议使用节省空间的发电机功能:
函数*展平(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]
要在一行中展平二维阵列,请执行以下操作:
[[1, 2], [3, 4, 5]].reduce(Function.prototype.apply.bind(Array.prototype.concat))
// => [ 1, 2, 3, 4, 5 ]
适用于所有数据类型的递归版本
/*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);
我认为最好的方法是这样:
var flatten = function () {
return [].slice.call(arguments).toString().split(',');
};
可以将Array.flat()与Infinity一起用于任何深度的嵌套数组。
var arr=[[1,2,3,4],[1,2,[1,2,3]],[1,2,4,5,[1,3,4,[12,3,4,[12,3,4]]],[[1,2,3-4],[1,3,[1,2],[1,2,3,5],[1,3,4,[1,2,3,4]]];let flatten=arr.flat(无限)console.log(展平)
在此处检查浏览器兼容性