我有一个JavaScript数组,如:

[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]

如何将单独的内部数组合并为一个,例如:

["$6", "$12", "$25", ...]

当前回答

可以将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(展平)

在此处检查浏览器兼容性

其他回答

我建议使用节省空间的发电机功能:

函数*展平(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]

我使用这个方法来展开混合数组:(这对我来说似乎最简单)。用较长的版本来解释步骤。

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)

在javascript中定义一个名为foo的数组数组,并使用javascript的arrayconcat内置方法将该数组展平为单个数组:

const foo = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]] 
console.log({foo}); 

const bar = [].concat(...foo) 
console.log({bar});

应打印:

{ foo: 
   [ [ '$6' ],
     [ '$12' ],
     [ '$25' ],
     [ '$25' ],
     [ '$18' ],
     [ '$22' ],
     [ '$10' ] ] }
{ bar: [ '$6', '$12', '$25', '$25', '$18', '$22', '$10' ] }

以下是Typescript中最快的解决方案,它也适用于具有多层嵌套的数组:

export function flatten<T>(input: Array<any>, output: Array<T> = []): Array<T> {
    for (const value of input) {
        Array.isArray(value) ? flatten(value, output) : output.push(value);
    }
    return output;
}

以及:

const result = flatten<MyModel>(await Promise.all(promises));

您可以继续使用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]