Array flattening is often encountered in development, such as tiling feeds with nested layers. This article summarizes several common scenarios for array flattening.

Implementation scheme

1. Use ES6 Flat

Function ingarray (ARr) {return arr.flat(Infinity)} // test const arr = [1, 2, [3, 4, [5, 6, [7, 8]]]] console.log(' flatteningArray ', flatteningArray(arr));Copy the code

Verify the effect of

2. Use the array toString() to convert strings

Function ingarray (arr) {return arr.toString().split(',').map((item) => parseFloat(item))} // test const arr = [1, 1, [3, 4, [5, 6, [7, 8]]]] console.log(' array flattening toString', flatteningArray(arr)); 2, [3, 4, [5, 6, [7, 8]]]] console.log(' array flattening toString', arr)Copy the code

Verification effect:

3. Circular recursive method

function flatteningArray(arr) { let result = []; for (let i = 0; i < arr.length; i++) { if (Array.isArray(arr[i])) { result = result.concat(flatteningArray(arr[i])); } else { result.push(arr[i]) } } return result; } // test const arr = [1, 2, [3, 4, [5, 6, [7, 8]]]] console.log(' array flattening loop recurse ', arr);Copy the code

Verify the effect of

4. Array some + []. Concat (… arr)

function flatteningArray(arr) { while (arr.some((item) => Array.isArray(item))) { arr = [].concat(... arr) } return arr; } // test const arr = [1, 2, [3, 4, [5, 6, [7, 8]]]] console.log(' array flatteningArray some method ', arr);Copy the code

conclusion

In comparison, flat method is relatively simple and is the future trend of official standard. For compatibility you can use toString or the array some + [].concat(… Arr), both of which are more ingenious; Cyclic recursion is a general implementation scheme and conforms to the general logic characteristics.

If this article is helpful to you, you are welcome to give the author a thumbs up and follow haha, progress together ~