zxdfe / FE-Interview

Every step counts
34 stars 1 forks source link

第30题:实现数组去重?你可以写多少种? #31

Open zxdfe opened 1 year ago

shuke-zhang commented 1 year ago

const arr = [1, 5, 9, 6, 1, 7, 3, 5, 6, 7]

  1. 双重for遍历数组
    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)
                }
            }
        }
  2. includes()
    const newArr = []
       for (let i = 0; i < arr.length; i++) {
           if (!newArr.includes(arr[i])) {
               newArr.push(arr[i])
           }
       }
  3. **indexof()**
    const newArr = []
       for (let i = 0; i < arr.length; i++) {
           if (newArr .indexOf(arr[i]) === -1) {
               newArr .push(arr[i])
           }
       }
  4. findIndex()
    const newArr= []
        for (let i = 0; i < arr.length; i++) {
            if (newArr.findIndex(el => el === arr[i]) === -1) {
                newArr.push(arr[i])
            }
        }
  5. Set
    const newArr= Array.from(new Set(arr))
  6. reduce()
    const newArr= arr.reduce((pre, cur) => {
            if (!pre.includes(cur)) {
                pre.push(cur)
            }
            return pre
        }, [])
ttizzyf commented 1 year ago
双重for循环去重
const arr = [1,2,3,4,6,2,3,4,1,5,6,8]
        const newArr = []
        for(let i = 0;i < arr.length;i++) {
            for(let j = i + 1; j< arr.length - i;j++) {
                if(arr[i] === arr[j]) {
                    arr.splice(j,1)
                }
            }
        }
        console.log(arr)
利用filter和indexOf实现去重
const arr = [1,2,3,4,6,2,3,4,1,5,6,8]
  const newArr = arr.filter((el,index) => {
       // 查找el第一次出现的位置,如果有下标与当前下标相同,则说明这是只出现过一次的元素,保留下来
        return arr.indexOf(el) === index
   })
console.log(newArr)
利用es6新增的set数据结构去重
// es6新增数据结构set,set对象可以存储任何类型的唯一值.
const arr = [1,2,3,4,6,2,3,4,1,5,6,8]
// 再将set转为数组,就实现了去重
const newArr = Array.from(new Set(arr))
console.log(newArr)