js數組去重、數據和對象去重

數組去重網上的方法有很多種,我這裏整理了幾個是按最高效率進行排序的。
先創建兩個數組:

   data () {
    return {
      playlist: ['1', '2', '3', '4', '5', '6'],
      list: ['1', '2', '3', '4']
    }
  }

提示一下,裏面兩個數組裏面有字符串、數字要去重的話,可以全部轉換爲字符串或者數字再進行去重,arr.map(String)或者arr.map(Number)

效率第一:for…of + Object
首先創建一個空對象,然後用 for 循環遍歷
利用對象的屬性不會重複這一特性,校驗數組元素是否重複

  distinct () {
      let arr = []
      arr = this.a.concat(this.b)
      // arr = arr.map(Number)
      let result = []
      let obj = {}
      for (let i of arr) {
        if (!obj[i]) {
          result.push(i)
          obj[i] = 1
        }
      }
      return result
    },
 }

效率第二:new Set()
ES6 新增了 Set 這一數據結構,類似於數組,但 Set 的成員具有唯一性
基於這一特性,就非常適合用來做數組去重了

distinct () {
      let arr = []
      /* Array.from() 方法從一個類似數組或可迭代對象創建一個新的,淺拷貝的數組實例。 */
      arr = Array.from(new Set([...this.a, ...this.b]))
      return arr
    },

效率第三:Array.sort()
首先使用 sort() 將數組進行排序,然後比較相鄰元素是否相等,從而排除重複項

arr.map(String)
 distinct () {
      let arr = this.a.concat(this.b)
      // arr = arr.map(Number)
      arr = arr.sort()
      let result = [arr[0]]
      for (let i = 1; i < arr.length; i++) {
        arr[i] !== arr[i - 1] && result.push(arr[i])
      }
      return result
    }

有時候會遇到一些比較複雜的情況,比如說一個是數組,一個是對象,數組裏面還包含對象,那麼這個要怎麼去重呢,這裏提供的方法如下:

data () {
    return {
      playlist: [{ id: 1, name: 'a' }, { id: 2, name: 'a' }, { id: 3, name: 'a' }, { id: 4, name: 'a' }, { id: 5, name: 'a' }],
      list: {
        data: [{ id: 1, name: 'a' }, { id: 2, name: 'a' }, { id: 3, name: 'a' }, { id: 4, name: 'a' }]
      }
    }
  },
  methods:{
    distinct() {
      const newData = []
      const playlist = this.playlist
      let list = this.list
      for (let i = 0; i < playlist.length; i++) {
        let flag = true
        for (let j = 0; j < list.data.length; j++) {
          if (playlist[i].id === list.data[j].id) {
            flag = false
            break
          }
        }
        if (flag) {
          newData.push(playlist[i]) // 這裏的newData push的是去重比較之後得出的數據
        }
      }
      list = list.data.concat(newData)
    }
  }
 

以後就是數據去重的方法,有興趣的同學可以一起進行研究一下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章