One, understand

  • Generates a new array with duplicate elements removed from the current array
  • Such as:,9,8,7,2,5,6,5,4,5,6,4,5 [6] = = >,9,8,7,2,5,4 [6]

Two, implementation code

  1. ForEach () and indexOf() explain that the nature of the double traversal, less efficient

  /* Takes an array as an argument and returns a deduplicated array */
  function unique (array) {
    // Define an empty array
    const resultArr = []
    // Loop over the unduplicated array
    array.forEach(item= > {
      // If the element exists in resultArr, add it if it does not
      if (arr.indexOf(item)===-1) {
        resultArr.push(item)
      }
    })
    / / return
    return resultArr
  }

Copy the code
  1. Use forEach() + object container to illustrate: only once through, more efficient

  /* Takes an array as an argument and returns a deduplicated array */
  function unique (array) {
    // Define the array to return
    const resultArr = []
    // Define an object
    const obj = {}
    // Loop over the unduplicated array
    array.forEach(item= > {
      // If obj does not change element attributes
      if(! obj.hasOwnProperty(item)) {// Add this attribute for obj without
        obj[item] = true
        resultArr.push(item)
      }
    })
    return resultArr
  }

Copy the code
  1. Use ES6 syntax description: simple coding
  // 1. ... + Set
  function unique1 (array) {
    /* The Set constructor takes an array and returns */ from the internal deleverage three-point operator that converts a Set to an array
    return [...new Set(array)]
  }

  // 2. from + Set
  function unique2 (array) {
    /* The Set constructor takes an Array and uses Array's FROM method to convert a Set to an Array and returns */
    return Array.from(new Set(array))
  }

Copy the code