We're looking for a user researcher to understand the needs of developers and designers. Is this you or someone you know? Check out the post: https://mzl.la/2IGzdXS

I volontari di MDN non hanno ancora tradotto questo articolo in Italiano. Unisciti a noi e traducilo tu stesso.
Puoi anche consultare l’articolo in English (US).

This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The flat() method creates a new array with all sub-array elements concatted into it recursively up to the specified depth.

Syntax

var newArray = arr.flat(depth)

Parameters

depth Optional
The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.

Return value

A new array with the sub-array elements concatted into it.

Examples

Flattening nested arrays

var arr1 = [1, 2, [3, 4]];
arr1.flat(); 
// [1, 2, 3, 4]

var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

Flattening and array holes

The flat method removes empty slots in arrays:

var arr4 = [1, 2, , 4, 5];
arr4.flat();
// [1, 2, 4, 5]
 

Alternative

reduce and concat

var arr1 = [1, 2, [3, 4]];
arr1.flat();

//to flat single level array
arr1.reduce((acc, val) => acc.concat(val), []);
// [1, 2, 3, 4]

//to enable deep level flatten use recursion with reduce and concat

var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];

(function flattenDeep(arr1){
   return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
})(arr1);

// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]


Specifications

Specification Status Comment
Array.prototype.flat proposal Draft  

Browser compatibility

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support No No No1 No No No
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Basic support No No No No1 No No No

1. Available in Firefox Nightly only. See bug 1435813 for status on enabling this by default.

See also

Tag del documento e collaboratori

Hanno collaborato alla realizzazione di questa pagina: schlagi123, wmsbill, carrola7, mkumary, michaelficarra, rwaldron, Baptistou, fscholz, evilpie
Ultima modifica di: schlagi123,