关于javascript:js变态数组去重多类型item复杂嵌套

236次阅读

共计 826 个字符,预计需要花费 3 分钟才能阅读完成。

申明一个比拟芜杂的数组:

let arr = [1, 'a', { b: 2}, {c: 3}, {b: 2}, {a: 2, b: { a: 123} }, false, null, false, undefined, null, {a: 2, b: { a: 123} }, '1', 'a', [1, 2, 3], [6, 6, 6], [1, 2, 3], [{a: 1}, {b: 1}, 1, 2, 3], [{a: 1}, {b: 1}, 1, 2, 3], undefined]

这个数组中蕴含了较为丰盛的数据类型:Object、Array、Number、String、null、undefined,其中的 Object 还有多层嵌套

解法:


function unique (arr) {let obj = {}
  let ret = []
  for (let i = 0; i <= arr.length - 1; i++) {const cur = arr[i]
    if (cur instanceof Object) {
      let isEqual = ret.some(item => {if (item instanceof Object) {return assertObj(item, cur)
        }
        return false
      })
      if (!isEqual) {ret.push(cur)
      }
      continue
    }

    if (!obj[typeof cur + cur]) {obj[typeof cur + cur] = true
      ret.push(cur)
    }
  }
  return ret
}

function assertObj (cur, next) {if (Object.keys(cur).length !== Object.keys(next).length) {return false}

  for (let key in cur) {if (cur[key] instanceof Object) {return assertObj(cur[key], next[key])
    }
    if (cur[key] !== next[key]) {return false}
  }

  return true
}

console.log(unique(arr))

正文完
 0