preface

Array flattening and de-duplication are two of the most frequent occurrences in interviews, so we need to pay attention to them. This article is based on dead knock 36 handwritten questions written, interested in can go to see it!

Array to heavy

Front-end updates are fast, so every problem has many solutions, we need to accept the new things, but also can not let go of the old things. Like array deduplication, es5 solution and ES6 solution is completely different, although es6 solution is much simpler, but es5 solution we also want to understand ah!

Without further ado, code first!

ES5 implementation:

function unique(arr) { var res = arr.filter(function(item, index, Array.indexof (item) === index}) return res} console.log(unique([1,2,2,3,4,55,55])) //[1,2,3,55]Copy the code
  1. The filter() method creates a new array of elements by checking all eligible elements in the specified array.

  2. The indexOf() method returns the location of a specified element in an array.

This method retrieves the array from beginning to end to see if it contains the corresponding element. Start the search at the start of the array or at the beginning of the array (when no start argument is specified). If an item is found, the first occurrence of the item is returned. The index of the starting position is 0.

Returns -1 if the specified element is not found in the array.

Tip: If you want to find the last position of a string, use the lastIndexOf() method.

ES6 implementation:

Var unique = arr = > new Set (arr) [...] the console. The log (unique (,2,2,3,4,55,55 [1])) / /,2,3,55 [1]Copy the code
  1. . Is the extension operator (object expansion)

The spread operator (spread) is three points (…) . It is like the inverse of the REST argument, turning an array into a comma-separated sequence of arguments.

extension

Extension operators can not only de-duplicate arrays, but also merge arrays

Let a = [1, 2, 3] let b = [4] 2 let c = [... a, b] the console. The log (c) / / var unique,2,3,2,3,4 [1] = arr = > new Set (arr)] [... The console. The log (unique (c)) / / [1, 2, 3, 4]Copy the code

Array flattening

Array flattening is to flatten a multilayer array like [1, [2, [3]] into a single layer [1, 2, 3]. Use array.prototype. flat to flatten an Array into a single layer:

[1, [2, [3]]].flat(2)  // [1, 2, 3]
Copy the code
  1. Array.prototype.flat() is used to “flatten” nested arrays into one-dimensional arrays. This method returns a new array with no effect on the original data.

  2. When no parameter is passed, a layer is “leveled” by default, and an integer can be passed to indicate the number of layers you want to “leveled”. Passing an integer <=0 returns the original array, not “flattened”

  3. When the Infinity keyword is used as a parameter, it is converted to a one-dimensional array no matter how many layers are nested

  4. If the Array has a void, array.prototype.flat () skips the void.

ES5 implementation: recursive.

The code! The code!

function flatten(arr) {
    var result = [];
    for (var i = 0, len = arr.length; i < len; i++) {
        if (Array.isArray(arr[i])) {
            result = result.concat(flatten(arr[i]))
        } else {
            result.push(arr[i])
        }
    }
    return result;
}
Copy the code

Flatten is an approach based on LoDash. And the flatten and flattening deep methods in Lodash can flatten an array. What is Lodash? Lodash is a consistent, modular, high-performance JavaScript utility library.

Lodash is distributed under the MIT Open Source license and supports the latest operating environment. Look at the differences between component versions and choose one that works for you.

Why Lodash?

Lodash makes JavaScript easier by making it easier to use arrays, Numbers, objects, Strings, and so on. Lodash’s modular approach is ideal for:

Traverses array, Object, and String

Manipulate and test values

Create functions that conform to functionality

You can avoid recursion by extending the operators, but you need to use loops. If the array is too hierarchical, the loops are expensive. What if you don’t use loops at all?

Using a string, using the re to remove the parentheses, is the simplest implementation, and the cost is minimal:

/ / flattened array (do not use cycle, using a string) function flatten (arr) {let STR = JSON. The stringify (arr). Replace (/ \ [| \] / g, "); return JSON.parse(Array.of('[' + str + ']')[0]); }Copy the code

In fact, if there is no extreme data, using toString() and then splitting the composition can also be flat, but not perfectly, such as the following data:

Let arr = [2, [3.2, [s,d,w '], 'a,b,c,d,e']; Arr. ToString () = = > "2,3.2, s, d, w, a, b, c, d, e"Copy the code

ES6 implementation:

function flatten(arr) { while (arr.some(item => Array.isArray(item))) { arr = [].concat(... arr); } return arr; }Copy the code

Recursion is a performance drain. You have to recreate the function every time. Can you do it without recursion? So ES6 has an expansion operator, an expansion operator, that can expand an array, one layer at a time, through a loop that flattens the array.

conclusion

Array de-duplication and array flattening I can introduce is also so much, of course, there are still many shortcomings need me to learn, so I will continue to work hard, welcome everyone more advice.