Array to focus on in the interview and work are relatively easy to see the problem, these days in the review of basic knowledge, but also summed up the common methods, and share with you. If you have any other ideas please feel free to comment and discuss them. If there is something wrong, please correct it.

001. Use doubleforcycle

To compare each value in an array we can use a double for loop, such as bubble sort. You can also use a double for loop to de-duplicate arrays.

function unique(arr) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = i+1; j < arr.length; j++) {
      if (arr[i] == arr[j]) {
        arr.splice(j,1)
        j--
      }
    }
  }
  return arr
}
let arr = [1.1.'true'.'true'.'a'.'a'.true.true.false.false.undefined.undefined.null.null.NaN.NaN.'NaN'.'NaN'.0.0, {}, {}, [], []];console.log(unique(arr)) // [ 1, 'true', 'a', false, undefined, NaN, NaN, 'NaN', {}, {} ]
Copy the code

As you can see, NaN is not removed, neither {} is removed, because {} is a reference value, but we use arr[I] == arr[j], which will be cast, so the following is true:

  • 1 == true
  • false== []
  • undefined == null
  • false == 0

Is (arr[I], arr[j]) instead of arr[I]==arr[j] can remove NaN and prevent type conversions. I can’t post the code here, but you can write it and run it yourself.

Note: ArR values are used for the convenience of the following ARRS

Second, the use ofindexOf()

IndexOf () determines whether an array contains a value and returns the element’s position in the array if it does, or -1 if it does not.

functon unique(arr) {
    let res = []
  	for (let i = 0; i < arr.length; i++) {
        if (res.indexOf(arr[i]) === -1) {
          	res.push(arr[i])
        }
  	}
  	return res
}
console.log(unique(arr)) //[ 1,   'true',   'a',   true,   false,   undefined,   null,   NaN,   NaN,   'NaN',   0,   {},   {}, [], []]
Copy the code

Here we create a new array to hold the de-duplicated array. If the array does not contain elements, we push the element into the array. We can see that NaN, {}, [] are still not removed.

Three, useincludes()

The includes() method is also used to determine whether an array contains a specific element, returning true if it does and false if it does not. This is somewhat similar to the indexOf() method, so we use includes() for array de-duplication in the same way as indexOf().

functon unique(arr) {
    let res = []
    for (let i = 0; i < arr.length; i++) {
        if(! res.includes(arr[i])) { res.push(arr[i]) } }return res
}
Copy the code

Four, the use offilter()

The filter() method creates a new array of elements by checking all eligible elements in the specified array. And filter() does not change the array, nor does it detect an empty array. The filter() method receives a callback function.

Grammar:

array.filter(function(item,index,arr), thisValue)
Copy the code
parameter describe
item Must be. The value of the current element
index Optional. The index value of the current element
arr Optional. The array object to which the current element belongs

Code implementation

function unique(arr) {
    return arr.filter((item,index, arr) => {
        return arr.indexOf(item) === index
    })
}
console.log(unique(arr)) //[ 1, 'true', 'a', true, false, undefined, null, 'NaN', 0, {}, {}, [], [] ]
Copy the code

Here we use indexOf(item) to determine whether the current element’s index is equal to the current index, and return the element if it is equal.

Five, the characteristics of the object

An object is a structure that stores information in key-value pairs and cannot have duplicate keys.

function unique(arr) { let obj = {} for (let i = 0; i < arr.length; I ++) {if (arr[I] in obj) {obj[arr[I]] ++} else {obj[arr[I]] = 10}} return object.keys (obj) // console.log(unique(arr)) // [ '0', '1', 'true', 'a', 'false', 'undefined', 'null', 'NaN', '[object Object]', '']Copy the code

Keys (obj) returns the set of keys, so all the returns are strings.

Use set

ES6 provides a new data structure, Set. It is similar to an array, but the values of the members are unique and there are no duplicate values.

function unique(arr) {
  return [...new Set(arr)]
}
console.log(unique(arr)) //[ 1,   'true',   'a',   true,   false,   undefined,   null,   NaN,   'NaN',   0,   {},   {},   [],   [] ]
Copy the code

This is the most common approach for ES6, and it works just fine.

7. Reduce

function unique(arr) {
    return arr.reduce((pre, cur) = > {
        !pre.includes(cur) && pre.push(cur)
        return pre
    }, [])
}
Copy the code