js数组去重

function isPrimitive(obj) {
  return obj === null || !['object', 'function'].includes(typeof obj)
}
function objEqual(obj1, obj2) {
  //console.log(isPrimitive(obj1) || isPrimitive(obj2))
  if (isPrimitive(obj1) || isPrimitive(obj2)) {
    return Object.is(obj1, obj2)
  }
  const obj1Entry = Object.entries(obj1);
  const obj2Entry = Object.entries(obj2);
  console.log(obj1Entry)
  if (obj1Entry.length !== obj2Entry.length) {
    return false
  }
  for (const [k1, v1] of obj1Entry) {
    if (!(k1 in obj2) || !objEqual(v1, obj2[k1])) {
      return false;
    }
  }
  return true
}

function uniqueArray(arr) {
  let newArr = []
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i]
    let isFind = false
    for (let j = 0; j < newArr.length; j++) {
      const item1 = newArr[j]
      if (objEqual(item, item1)) {
        isFind = true
        break
      }
    }
    if (!isFind) {
      newArr.push(item)
    }
  }
  return newArr
}

const arr = [{ 'a': 1, 'b': 2 }, { 'a': 1, 'c': undefined }, { 'b': 2, 'a': 1 }, null, null, undefined, undefined, { 'aa': { 'bb': 1 } }, { 'aa': { 'bb': 1 } }]

console.log(uniqueArray(arr))

 

posted @ 2024-04-28 14:47  howhy  阅读(3)  评论(0编辑  收藏  举报