[Interview question] How to realize deduplication of array? How many ways are there?

 Front-end interview question bank ( necessary for interview) recommendation: ★★★★★            

Address: front-end interview question bank

[National Day Avatar] - National Day patriotic programmer avatar! always one option fit for you!

1. Method 1: Using the splice method of two layers of loop + array

The array elements are compared one by one through two layers of loops, and then the duplicate elements are deleted through the splice method. This method cannot deduplicate NaN , because when comparing NaN !== NaN.

let arr = [1, 2, 2, 'abc', 'abc', true, true, false, false, undefined, undefined, NaN, NaN]
function removeDuplicate(arr) {
  let len = arr.length
  for (let i = 0; i < len; i++) {
    for (let j = i + 1; j < len; j++) {
      if (arr[i] === arr[j]) {
        arr.splice(j, 1)
        len--
      }
    }
  }
  return arr
}
removeDuplicate(arr)
console.log(arr) // [ 1, 2, 'abc', true, false, undefined, NaN, NaN ]

2. Method 2: Use Set()+Array.from()

  • SetObject: is a collection of values ​​whose elements you can iterate over in the order they were inserted . The elements in the Set will only appear once , that is, the elements in the Set are unique .
  • Array.from() Method: Create a new, shallow copy of an Array instance of an Array-like or Iterable object .
function removeDuplicate(arr) {
  // return [...new Set(arr)]
  return Array.from(new Set(arr))
}
 // [ 1, 2, 'abc', true, false, undefined, NaN ]

3. Method 3: Use the indexOf method of the array

Create an empty array, traverse the array that needs to be deduplicated, and store the array elements in the new array. Before storing, determine whether the array already contains the current element, and if not, store it. This method also fails to NaNdeduplicate

  • indexOf() Method: Returns the index of the first occurrence of the specified value in the String object that called it, from  fromIndex which to search. Returns -1 if the value is not found
function removeDuplicate(arr) {
  let newArr = []
  arr.map(item => {
    if (newArr.indexOf(item) === -1) {
      newArr.push(item)
    }
  })
  return newArr
}
console.log(removeDuplicate(arr)) // [ 1, 2, 'abc', true, false, undefined, NaN, NaN ]

4. Method 4: Use the includes method of the array

The logic of this method is similar to that of the indexOf method, except that the includes method is used to determine whether duplicate elements are included.

  • includes()Method: used to judge whether an array contains a specified value, according to the situation, return if it contains  true, otherwise return  false.
function removeDuplicate(arr) {
  let newArr = []
  arr.map(item => {
    if (!newArr.includes(item)) {
      newArr.push(item)
    }
  })
  return newArr
} // [ 1, 2, 'abc', true, false, undefined, NaN ]

Note : Why includesit is possible to detect the inclusion in the array NaNinvolves includesthe underlying implementation. The following figure includesshows part of the code implemented. When judging whether an element is contained, it will be called for sameValueZero方法comparison, and if it is NaN, it will be used isNaN()for conversion.

For specific implementation, please refer to: developer.mozilla.org/zh-CN/docs/…

image-20211211182654658.png

Simple test includes()for NaNjudgment:

简单测试includes()对NaN的判断:
const testArr = [1, 'a', NaN]
console.log(testArr.includes(NaN)) // true

5. Method 5: Use the filter()+indexOf() of the array

The filter method will store the elements that meet the conditions in a new array, and use the indexOf method to judge.

  • filter() Method: Creates a new array containing all elements of the test implemented by the provided function .
function removeDuplicate(arr) {
  return arr.filter((item, index) => {
    return arr.indexOf(item) === index
  })
}

const result = removeDuplicate(arr)
console.log(result) // [ 1, 2, 'abc', true, false, undefined ]

Note : The output result here is not included NaN, because indexOf()NaN cannot be judged, that is, arr.indexOf(item) === indexthe returned result is false. The test is as follows:

const testArr = [1, 'a', NaN]
console.log(testArr.indexOf(NaN)) // -1

6. Using Map()

The Map object is a data structure provided by JavaScript. The structure is in the form of key-value pairs. The array elements are stored as the keys of the map, and then combined with the has()and set()method to determine whether the key is repeated.

  • Map Object: used to save key-value pairs, and can remember the original insertion order of keys. Any value (object or primitive) can be used as a key or a value.
function removeDuplicate(arr) {
  const map = new Map()
  const newArr = []

  arr.forEach(item => {
    if (!map.has(item)) { // has()用于判断map是否包为item的属性值
      map.set(item, true) // 使用set()将item设置到map中,并设置其属性值为true
      newArr.push(item)
    }
  })

  return newArr
}
-----------------或者-------------------------------------------------------
function removeDuplicate(arr) {
  let map = new Map()
  arr.map(item => {
    if (!map.has(item)) map.set(item)
  })
  return [...map.keys()]
}

const result = removeDuplicate(arr)
console.log(result) // [ 1, 2, 'abc', true, false, undefined, NaN ]

Note : use Map()can also be used to deduplicate, the reason is that Map is considered to be equal NaNwhen judging , and all other values ​​​​are   judged to be equal according to the result of the operator.NaNNaN===

7. Use object

In fact, the implementation idea Map()is similar to that, mainly because the attribute name of the object cannot be repeated.

function removeDuplicate(arr) {
  let obj = {}
  arr.map(item => {
    if (!obj[item]) {
      obj[item] = true
    }
  })
  return Object.keys(obj)
}

 Front-end interview question bank ( necessary for interview) recommendation: ★★★★★            

Address: front-end interview question bank

[National Day Avatar] - National Day patriotic programmer avatar! always one option fit for you!

おすすめ

転載: blog.csdn.net/weixin_42981560/article/details/132697323