我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
我有一个JavaScript数组,如:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
如何将单独的内部数组合并为一个,例如:
["$6", "$12", "$25", ...]
当前回答
我建议使用节省空间的发电机功能:
函数*展平(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]
其他回答
如果你使用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)
您可以继续使用Array.flat()方法来实现这一点,即使数组嵌套得更多。
[1,2,3,[2]].flat()
相当于
[1,2,3,[2]].flat(1)
所以当你的筑巢增加时,你可以继续增加数量。
eg:
[1,[2,[3,[4]]]].flat(3) // [1, 2, 3, 4]
如果您不确定嵌套的级别,可以只传递Infinity作为参数
[1,2,3,[2,[3,[3,[34],43],[34]]]].flat(Infinity) //[1, 2, 3, 2, 3, 3, 34, 43, 34]
我使用这个方法来展开混合数组:(这对我来说似乎最简单)。用较长的版本来解释步骤。
function flattenArray(deepArray) {
// check if Array
if(!Array.isArray(deepArray)) throw new Error('Given data is not an Array')
const flatArray = deepArray.flat() // flatten array
const filteredArray = flatArray.filter(item => !!item) // filter by Boolean
const uniqueArray = new Set(filteredArray) // filter by unique values
return [...uniqueArray] // convert Set into Array
}
//较短版本:
const flattenArray = (deepArray) => [...new Set(deepArray.flat().filter(item=>!!item))]
flattenArray([4,'a', 'b', [3, 2, undefined, 1], [1, 4, null, 5]])) // 4,'a','b',3,2,1,5
Codesandbox链接
现代方法
使用[].flat(Infinity)方法
const nestedArray = [1,[2,[3],[4,[5,[6,[7]]]]]]
const flatArray = nestedArray.flat(Infinity)
console.log(flatArray)
更简单和直接的方法;可选择深压平;
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
我建议使用节省空间的发电机功能:
函数*展平(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]