Double loop

  • Double loops are two for loops to implement array de-duplication, which is the most compatible, but poor performance if the array is too large.
function unique(array) {
    let result = []
    for(var i = 0; i < array.length; i++){
        for(var j = 0; j < result.length; j ++){
            if(array[I] === result[j]) {if (array[I] === result[j]) {if (array[I] === result[j]) {if (array[I] === result[j]) {if (array[I] === result[j]) {if (array[I] === result[j])ifThe statement will not executebreak}} // If result does not have the same item as array[I], then the second layerforWhen the loop is complete, j === result.length // and array[I] of this loop is pushed to resultif (j === result.length) {
            result.push(array[i])
        }
    }
    return result
}
Copy the code

Use the indexOf() method

  • IndexOf () checks if the specified value exists in the array and returns the index, or -1 if not
function unique(array) {
    var res = []
    for (var i = 0; i < array.length; i ++){
        if (res.indexOf(array[i]) === -1) {
            res.push(array[i])
        }
    }
    return res
}
Copy the code

The filter() method of ES5 is combined with indexOf() to remove the weight

  • The filter() method can filter an array, returning the filtered array without changing the original array
function unique(array) {
    returnArray.filter ((item, index, self) => self.indexof (item) === index) // [1,1,1,1].indexof (1) returns the first'1'The first index is not queried'1'The next element. Self.indexof (item) returns the index 0 every time except for the first element (index = 0), after which the equation fails. }Copy the code

Deduplication is implemented through the key-value of the object

  • Objects have a hasOwnProperty() method that finds if the object contains a key and returns a Boolean value
  • Notice what happens if we define an object like the following?
var obj = {
    1: 'number1'.'1': 'string1'
}
Copy the code
  • The answer is that the string ‘1’ will overwrite the number 1. With that little detail in mind, we’ll implement the de-weight method.
function unique(array) {
    var obj = {}
    returnArray. filter((item, index, self) => {// If typeof item + item is not found in the object, add a key to it: typeof item + item, value set totrueIs filtered out. // value can be set arbitrarily, except 0,' 'Phi,undefined, et cetera, these will convert to phifalseValue the value of thereturn obj.hasOwnProperty(typeof item + item) ? false : obj[typeof item + item] = true})}Copy the code

Finally, we can use a new data result in ES6 called a Set, which is similar to an array but has unique entries with no duplicate values.

The Set itself is a constructor used to generate the Set data structure.

  1. Instances of the Set structure have the following properties.

    • Set. The prototype. The constructor: constructor, the default is Set function.
    • Set.prototype.size: Returns the total number of members of a Set instance.
  2. The methods of a Set instance fall into two broad categories: operation methods (for manipulating data) and traversal methods (for traversing members).

    • Add (value) : Adds a value and returns the Set structure itself.
    • Delete (value) : deletes a value and returns a Boolean value indicating whether the deletion is successful.
    • Has (value) : Returns a Boolean value indicating whether the value is a member of Set.
    • Clear () : Clears all members with no return value.
    • Keys () : returns a traverser for key names
    • Values () : Iterator that returns key values
    • Entries () : Returns a traverser for key and value pairs
    • ForEach () : Iterates through each member using the callback function
Var uniqueArr = new Set([1,2,3,1, 0, 0, 0, 0, 0, 0, 0, 0)'1'.'a'.'a'])

>>>uniqueArr
<<< Set(5) {1, 2, 3, "1"."a"}

>>> uniqueArr instanceof Array
<<< false
Copy the code
  • As you can see, the result is Set data, so how do you return an array? This comes with another array method that ES6 provides
  • The array. from(obj, fn, context) method converts an array-like object or traversable object into a real Array. It can take three arguments, the first is the object to be converted, and the second is a function that executes each item of the object and returns the processed item. Context specifies the this object that executes fn

Now that we understand the usage, let’s look at how to use a Set to implement array de-duplication

function unique(array) {
    return Array.from(new Set(array))
}
Copy the code

You can also skip the array.from () method and use ES6 ‘… ‘extends the operator

function unique(array) {
    returnVar unique = (array) => [...new Set(array)]Copy the code

Conclusion: We have seen that there are many ways to de-duplicate arrays, but all of these are dealing with basic data types, but when we encounter objects in arrays, we need to take a different approach. Take a look at this example:

>>> NaN === NaN
<<< false

>>> NaN == NaN
<<< false

>>> {} == {}
<<< false

>>> {} === {}
<<< false

>>> undefined == undefined
<<< true

>>> undefined === undefined
<<< true

>>> null == null
<<< true

>>> null === null
<<< true
Copy the code