获取数组中重复的元素

第一种,判断包含基本类型的数组中的重复元素

/**
 * (这里只是判断基本类型的元素)
 * @param  Array
 * @return Array
 */
export const getRepeatElement = (array) => {
  let result = []
  let hash = {}
  array.forEach((item) => {
    if (item) {
      if (!hash[item]) {
        hash[item] = true
      } else {
        result.push(item)
      }
    }
  })

  result = result.filter((item, index, arr) => arr.indexOf(item) === index)

  return result
}

第二种,判断包含对象的数组中的重复元素

/* 去掉对象数组中属性和属性值一样的对象,返回过滤后的数组 */
const getNoRepeatObject = (array) => {
  if (array.length < 2) {
    return array
  }
  let differentObject = []  //放不重复的对象
  let sameObject = [] //放重复对象
  array.forEach(obj => {
    let sameArray = differentObject.filter(tempObj => {
      let isSame = true
      if(Object.keys(tempObj).length === Object.keys(obj).length) {
        for (const key in tempObj) {
          if (!obj.hasOwnProperty(key) || tempObj[key] !== obj[key]) {
            isSame = false
          }
        }
      } else {
        isSame = false
      }
      if (isSame) {
        return tempObj
      }
    })
    if (!sameArray.length) {
      differentObject.push(obj)
    } else {
      sameObject.concat(sameArray)  //将重复的对象放到sameObject数组中,如果需要,也可以返回
    }
  })
  if (differentObject.length === 1) {
    differentObject = []
  }

  return differentObject
}

猜你喜欢

转载自www.cnblogs.com/yyh1/p/9822257.html