常见的数组去重主要有俩方面:

  1. 由基本类型组成的数组去重
  2. 由对象组成的数组根据对象某个属性去重

基本类型去重:

export function unique(array) {
  const arr = []
  const contain = {}
  array.forEach(item => {
    if (!contain.hasOwnProperty(item)) {
      arr.push(item)
      contain[item] = true
    }
  })
  return arr
}

 效果:

 

根据对象属性去重:

/**
 * 
 * @param {Array} array 
 * @param {string} key ,对象属性名
 * @returns {Array}
 */
export function uniqueByAttr(array, key) {
  const hash = {};
  const arr = array.reduce((preVal, curVal) => {
    hash[curVal[key]]
      ? ""
      : (hash[curVal[key]] = true && preVal.push(curVal));
    return preVal;
  }, []);
  return arr;
}

效果:

 

 

脚踏实地行,海阔天空飞

 

posted on 2021-08-20 18:28  coder__wang  阅读(246)  评论(0编辑  收藏  举报