In front-end development, we can't avoid many arrays , There are many cases where arrays are nested or arrays need to be merged . Today, Xiao Qian will introduce how to flatten the array .
The concept of array flattening ： Arrays used to nest multiple layers “ Flatten ”, Into a one-dimensional array
Method 1 ： adopt concat Convert a two-dimensional array to a one-dimensional array
principle ： By extending the operator , Expand the inside of the array , And pass concat Concatenating two strings returns a new array .
Method 2 ： Use the array method join And string methods split Flatten the array
principle ： adopt join Method to convert an array to a string separated by dots , In the use of split Convert the converted String into an array of strings , adopt .map Method to convert an internal string to a number type
Method 3 ： Through regular methods and JSON.stringify Methods and array methods
principle ： First, convert the array to a string Use string matching regular rules Replace all '[' ']' It's similar to method two split It's mainly about converting strings into arrays ,map Convert a string array to a number
Method four ： Function recursion
principle ： Judge whether the current value is an array , If it's an array, call it recursively
Method five ： adopt reduce Method to flatten the array
principle ： Mainly through reduce In turn , Judge whether the current object is an array , If it is an array, a function recursion is performed to flatten all the arrays inside （ Similar to method four ）
Methods six ：ES6 The new method flat()
This article is from Qianfeng education , Reprint please indicate the source .