()
flat()The method is used to flatten a nested multi-layer array and return a new array. It does not change the original array. The flat method is very useful when dealing with multidimensional arrays, which can make array operations more flexible and concise.
grammar
flat() flat(depth)
parameter
depth (optional): Specifies the depth to flatten, the default value is 1.
Return value
A new array containing flat array elements.
usage
const arr = [0, 1, 2, [3, 4]] () // [0, 1, 2, 3, 4]
describe
The flat() method will be ignoredEmpty slots in sparse arrays
。
The flat() method isshallow copy method
, it will not change the original array.
It only needsthis
Value haslength
Attribute and integer key attributes are just the attributes. but,If you want to expand elements, they must be arrays
。
Implement flat method
From the above flat description, please pay attention to implementing these three points when implementing flat.
- A parameter is required, the default value is 1.
- flat ignores empty slots in sparse arrays.
- The expanded element must be an array.
= function (depth = 1) { // A parameter is required, the default value is 1 const result = [] const flatten = (arr, currentDepth) => { for (let i = 0; i < ; i++) { if ((arr, i)) { // Ignore empty slots of sparse arrays if ((arr[i]) && currentDepth < depth) { // The expanded element must be an array flatten(arr[i], ++currentDepth) } else { (arr[i]) } } } } flatten(this, 0) return result }
Test cases
= function (depth = 1) { const result = [] const flatten = (arr, currentDepth) => { for (let i = 0; i < ; i++) { if ((arr, i)) { if ((arr[i]) && currentDepth < depth) { flatten(arr[i], ++currentDepth) } else { (arr[i]) } } } } flatten(this, 0) return result } ('Flat Normal Array') const arr1 = [1, 2, [3, 4]] (()) (()) // [1, 2, 3, 4] const arr2 = [1, 2, [3, 4, [5, 6]]] (()) (()) // [1, 2, 3, 4, [5, 6]] const arr3 = [1, 2, [3, 4, [5, 6]]] ((2)) ((2)) // [1, 2, 3, 4, 5, 6] const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]] ((Infinity)) ((Infinity)) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ('Use flat in sparse array') const arr5 = [1, 2, , 4, 5] (()) (()) // [1, 2, 4, 5] const arr6 = [1, , 3, ["a", , "c"]] (()) (()) // [ 1, 3, "a", "c" ] const arr7 = [1, , 3, ["a", , ["d", , "e"]]] (()) (()) // [ 1, 3, "a", ["d", empty, "e"] ] ((2)) ((2)) // [ 1, 3, "a", "d", "e"] ('Use flat on non-array objects') const arrayLike = { length: 3, 0: [1, 2], 1: { length: 2, 0: 3, 1: 4 }, 2: 5, } ((arrayLike)) ((arrayLike)) // [1, 2, { "0": 3, "1": 4, "length": 2 }, 5]
Conclusion
At this point, the implementation of the Array instance method flat is completed.
This is the end of this article about the implementation of JavaScript Array instance method flat. For more related JavaScript Array flat implementation content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!