ES6 数组去重

  /**
   * 数组去重
   * @param {*} arr
   * 纯数组
   */
  function uniqueArray(arr) {
    if (!Array.isArray(arr)) {
      throw new Error('The first parameter must be an array')
    }
    if (arr.length == 1) {
      return arr
    }
    return [...new Set(arr)]
  }
  let array=[1,2,3,4,3,2,1,2,6]
  console.log(uniqueArray(array));//[1, 2, 3, 4, 6]

 

 /**
   * 对象数组去重
   * data:对象数组
   * key:筛选的字段
   */
  function uniqueArray(data,key) {
    let hash = {};
    data = data.reduce(function(item, next) {
      hash[next[key]] ? '' : hash[next[key]] = true && item.push(next);
      return item
    }, [])
    return data
  }
  let array=[{ id:1 },{ id:12 },{ id:3 },{ id:2 },{ id:1 },{ id:3 },{ id:12 },{ id:6 },{ id:11 },]
  console.log(uniqueArray(array,'id'));

  

 

posted @ 2021-10-21 09:21  小旺同学  阅读(62)  评论(0编辑  收藏  举报