What is array flattening
What is array flattening? Array flattening will be a multi-layer nested array into a single-layer array, such as: [1, [2, [3, [4, [5]]]]]—->[1,2,3,4,5] Array flattening as a classic interview question, today I will talk with you to achieve array flattening N ways.
7 ways to implement
1. arr.flat(Infinity)
Flat is a new feature in ES6 that allows you to flatten arrays quickly and simply by calling it. It’s easy to get started (it’s a zero threshold), but it’s not going to get your interviewers’ attention!
const arr = [1[2[3[4[5]]]]];
// 1. Flat automatically expands
let arr1 = arr.flat(Infinity);
console.log(arr1); // [1, 2, 3, 4, 5]
Copy the code
2. replace + split
Idea: Convert an array to a string, use a re to remove all brackets, and then generate a string from the remaining strings delimited by commas.
One drawback to this approach, however, is that each item in the resulting array is a string, not a number
const arr = [1[2[3[4[5]]]]];
// Turn arr into a string
let str = JSON.stringify(arr);
console.log(str); // [1,[2,[3,[4,[5]]]]] String
// 2. replace + split
// Use re to remove both [] symbols in STR
let arr2 = str.replace(/(\[|\])/g.' ');
console.log(arr2); / / 1, 2, 3, 4, 5
// Generate an array with, spacing
arr2 = arr2.split(', ');
console.log(arr2); //['1', '2', '3', '4', '5']
// This is a single line of code
let arr3 = str.replace(/(\[|\])/g.' ').split(', ');
console.log(arr3);// ['1', '2', '3', '4', '5']
Copy the code
3. replace + JSON.parse
Idea: Once again, convert to a string, remove all brackets, but finally surround the two with brackets, and call the json.parse method to automatically convert to an array
This method is a slight improvement over the previous one, and solves the problem that the generated array is all characters
const arr = [1[2[3[4[5]]]]];
// Turn arr into a string
let str = JSON.stringify(arr);
console.log(str); // [1,[2,[3,[4,[5]]]]] String
// 3. replace + JSON.parse
// Remove all parentheses first
let str2 = str.replace(/(\[|\])/g.' ');
// Add open and close brackets
str2 = '[' + str2 + '] ';
str2 = JSON.parse(str2); // The actual implementation of array flattening
console.log(str2); // [ 1, 2, 3, 4, 5 ] Array
Copy the code
4. The map
The idea of map is to take all the characters from the array, generate the array again and convert all the characters to numeric types, which is also an optimization of the second method above.
const arr = [1[2[3[4[5]]]]];
function flatten(arr) {
return arr.toString().split(', ').map(function (item) {
return +item //+ can quickly get the Number type})}console.log(flatten(arr)); // [1, 2, 3, 4, 5]
Copy the code
5. Extension operator (…)
This method borrows the Array. IsArray and some methods, and uses a while loop to continuously check if there is an Array in the Array. It is also a convenient way to expand it.
const arr = [1[2[3[4[5]]]]];
function Flatten(array) {
// Use array. isArray to determine whether an Array is nested
// Use the some method to control the while loop
while (array.some((item) = > Array.isArray(item))) {
// Expand the array and overwrite it againarray = [].concat(... array) }return array;
}
console.log(Flatten(arr));//[1, 2, 3, 4, 5]
Copy the code
6. Recursive functions
The recursion function also uses the array. isArray method, which is called recursively to expand if nested arrays are found in the Array.
const arr = [1[2[3[4[5]]]]];
function fn(array) {
let a = [];
for (let i = 0; i < array.length; i++){
// Make a recursive call if there is an array
if (Array.isArray(array[i])) {
a = a.concat(fn(array[i]));
} else { // No direct push existsa.push(array[i]); }}return a;
}
console.log(fn(arr)); / / [1, 2, 3, 4, 5]
Copy the code
7. The reduce thought
The reduce idea is to pass an empty array as the receiving object. It also uses the idea of recursion, expanding the array recursively and returning a one-dimensional array.
const arr = [1[2[3[4[5]]]]];
function Flatten(array) {
return array.reduce((pre, cur) = > {
// Determine whether there is an array. If there is an array, push it recursively
return pre.concat(Array.isArray(cur)? Flatten(cur):cur) },[])// Pass the empty array as the receiving object
}
console.log(Flatten(arr)); [1.2.3.4.5]
Copy the code
Write in the last
Array flattening can be said to be a relatively simple method, the method is also a variety of, here is just a list of several methods I am familiar with. There’s a better way and you’re welcome to comment in the comments section.
I am river, front intern a, welcome to each big guy didi, if the article is not correct please be corrected!