This is the 20th day of my participation in The August Wenwen Challenge.

Writing in the front

The idea of array flattening is to convert a multidimensional array into a one-dimensional array. Emm, explanation a little pale, see an example 🌰

const arr = [1[2.3].4];
const flatArr = [1.2.3.4];
Copy the code

In the above example, arr is a multidimensional array, and flatArr is a flattened array

Flat implementation

Interviewer: Please implement an array flattening

const flatArr = arr.flat(Infinity); // [1, 2, 3, 4]
Copy the code

The flat() method creates a new array in which all the subarray elements are recursively connected to the specified depth.

Here we use the es6 array method flat and pass in an Infinity to indicate that the array can be flat no matter how deep it is.

Interviewer: Is there any other way?

We can do it in other ways, too. Let’s take a look.

Using regular matching

const jsonArr = JSON.stringify(arr);
const flatArr = jsonArr.replace(/\[|\]/g.' ').split(', ');
Copy the code

So we serialize the ARR first, then replace the brackets in the global matching string with an empty string, which removes all the brackets in the multidimensional array, and then split the string into an array.

ToString intercepts the brackets

const flatArr= String(arr).split(', ');
Copy the code

In fact, the overall idea is the same with the use of regular matching, but the writing is more simple, we just need to brainless (clever) array to replace the group to pay, and then segmented.

recursive

function flatten(arr) {  
    return arr.reduce((result, item) = > {
        return result.concat(Array.isArray(item) ? flatten(item) : item); } []); }const flatArr = flatten(arr);
Copy the code

Well, this is a little bit more horizontal, we use recursion, define an accusation group, and then loop through each item, if the current item is a number, we continue to call the recursive function, otherwise it is not an array, we concat into the array.

conclusion

The simplest and most efficient way to flatness is to use the native method of array flat. We can use it directly if it can be used in the project. But when you go to an interview, you need to master a different approach.

There are actually two main categories of methods explained here. One is to convert it into a string and then split it into an array. The other one is to just recurse, and then determine if it’s an array, and then decide if it’s recursive, or put it in a new array.

The front end is long and long. We are all on the road. We hope to communicate with our friends and make progress together. Keep updating ing…..