Array flattening is the conversion of a nested array (which can be any number of layers) to an array with only one layer.
For example, suppose there is a function called flatten that flattens arrays,
var arr = [1[2[3.4]]];
console.log(flatten(arr)) // [1, 2, 3, 4]
Copy the code
The first thing we can think of is to loop through an array element. If it is still an array, we call this method recursively:
// This method is implemented recursively, when the element is an array recursively, good compatibility
function flattenArray(array) {
if (!Array.isArray(array)) return;
let result = [];
result = array.reduce(function (pre, item) {
// Check whether the element is an array. If it is an array, it is called recursively. If not, it is added to the result array
return pre.concat(Array.isArray(item) ? flattenArray(item) : item); } []);return result;
}
// This method makes use of the toString method, which has the disadvantage of changing the type of the element. It only works if the elements in the array are integers
function flattenArray(array) {
return array.toString().split(",").map(function (item) {
return+item; })}Copy the code