This is the sixth day of my participation in Gwen Challenge

The original intention of this series of articles is to “let each front-end engineer master the high frequency knowledge, for the work of power”. This is the front end of the 20th cut, I hope friends pay attention to the public number “kite”, armed with knowledge of their minds.

20.1 background

Have you ever encountered an interview question: How to expand a multidimensional array into a one-dimensional array? At that time, I did not know the magic method of Flat, so I used the most traditional solution to solve the problem.

const flatten = arr= > arr.toString().split(', ').map(item= > +item);

const arr = [1.2[3.4[5.6]]];
console.log(flatten(arr)); // [1, 2, 3, 4, 5, 6]
Copy the code

The above method is not a magic way to expand a multilevel array into a single level, but there are some serious problems with this method. Let’s take a look at these problems.

  1. No matter how many levels it’s going to expand into one level;
  2. The result is actually a string that needs to be converted to the original type.

Based on this opportunity, WE found that ES6 added the flat function, which is born for data flattening.

20.2 flat base

The Flat () method recurses through the array of numbers at a specified depth and returns all the elements in a new array combined with the elements in the traversed subarray.

  1. The flat method is used as follows:
const newArray = arr.flat([depth])
Copy the code
  1. A profound
const arr = [1.2[3.4[5.6]]];
console.log(arr.flat(1)); // [1, 2, 3, 4, [5, 6]]
console.log(arr.flat(2)); // [1, 2, 3, 4, 5, 6]
Copy the code

20.3 implementation

Flat smells so good, so can we make one ourselves? There are many ways to implement this approach, so let’s take a look at five of them. (Note: These five methods try the alternatives given in MDN.)

20.3.1 Using Reduce and Concat

While this approach is simple to implement, it has a major drawback: you can only expand one layer, and you won’t be able to do anything about multiple layers. The idea can be summarized as the following two steps:

  1. Use the reduce function to process each array element in turn;
  2. Use concat to add the current array element (value or subarray) to the result array.
Flat1 = function () {return this.reduce((acc, val) => acc.concat(val), []); }Copy the code

20.3.2 Use Reduce + concat + isArray + recursivity

This approach already has the ability to expand multiple layers, and its implementation ideas can be summarized as follows:

  1. Use the reduce function to process each array element in turn;
  2. Add the current element to the result array using concat;
  3. Use isArray to check whether the elements in the current array are an array.
  4. Use recursion to expand multilevel arrays.
Prototype. Flat2 = function (deep = 1) {const flatDeep = (arr, deep = 1) => { return deep > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, deep - 1) : val), []) : arr.slice(); } return flatDeep(this, deep); }Copy the code

ForEach + concat + isArray +recursivity

This approach is similar to the above approach in that hierarchical expansion can be set, but the traversal array is converted from Reduce to forEach.

Array.prototype. Flat3 = function (deep = 1) {const  result = []; (function flat(arr, deep) { arr.forEach((item) => { if (Array.isArray(item) && deep > 0) { flat(item, deep - 1); } else { result.push(item); } }) })(this, deep); return result; }Copy the code

For of + concat + isArray +recursivity

This method is similar to the above method, with the ability to set the hierarchy expansion, but traversal groups using the for of method

Array.prototype. Flat4 = function (deep = 1) {const for (concat + isArray +recursivity) result = []; (function flat(arr, deep) { for(let item of arr) { if (Array.isArray(item) && deep > 0) { flat(item, deep - 1); } else {// remove empty elements because void expressions return undefined, undefined is not used because undefined locally overrides item! == void 0 && result.push(item); } } })(this, deep); return result; }Copy the code

20.3.5 Using the Stack Stack

This method mainly uses the idea of stack to expand a multi-layer array into one layer. Its idea can be summarized as the following steps:

  1. The array to be processed is placed on a stack;
  2. Take out the element from the top of the stack, determine the type of the element, if it is an array, expand the array and put it back to the top of the stack; If it is a normal element, place it in the result;
  3. Loop through until the stack is empty.
Flat5 = function() {const stack = [...this]; const result = []; while (stack.length > 0) { const next = stack.pop(); if (Array.isArray(next)) { stack.push(... next); } else { result.push(next); Return result.reverse(); return result.reverse(); }Copy the code

1. If you think this article is good, share and like it so that more people can see it

2. Pay attention to the public number of kite, and the number of the Lord together to kill the front hundred