1. Requirements:
Convert the array [1, 2, [3, 4, [5, 6]], 7, [8, [9, 10]]] to [1, 2, 3, 4, 5, 6, 7, 8, 9,10]
2. Implementation method:
(1) map plus recursion
Idea: prepare an empty array first, map traverses the original array and uses Array.isArray() to determine whether each item of the array is an array, if one of the items is an array, continue traversing through the recursive function, if it is not an array, add it to In the prepared empty array
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const numList = [1, 2, [3, 4, [5, 6]], 7, [8, [9, 10]]];
function expandArr (arr) {
const newArr = []
function mapArr (arr) {
arr.map(item => Array.isArray(item) ? mapArr(item) : newArr.push(item))
return newArr
}
return mapArr(arr)
}
const res = expandArr(numList)
console.log(res, 'final result');
</script>
</body>
</html>
(2) reduce plus recursion (optimization of the first method)
Idea: reduce traverses the original array and uses Array.isArray() to determine whether each item of the array is an array. If it is an array, continue traversing through recursion. If it is not an array, merge the current item with the result until the reduce method returns the last accumulated result
const numList = [1, 2, [3, 4, [5, 6]], 7, [8, [9, 10]]];
function expandArr (arr) {
return arr.reduce((newArr, item) => newArr.concat(Array.isArray(item) ? expandArr(item) : item), [])
}
const res = expandArr(numList)
console.log(res, 'final result');
For the use of various methods of arrays, you can refer to my other article:
Title: What are the parameters and return values of the operation array method? Address: https://mp.csdn.net/mp_blog/creation/editor/128056253