数组去重——数组中有数组以及对象

95 阅读1分钟
const temp = [
  "1",
  "1",
  undefined,
  undefined,
  null,
  null,
  NaN,
  NaN,
  { a: 1 },
  { a: 1 },
  [2, 4, 5],
  [2, 4, 5],
];
const arr = [];
const map = new Map();
for (let i = 0; i < temp.length; i++) {
  let mid;
  // console.log(typeof temp[i]);
  if (typeof temp[i] === "object") {
    mid = temp[i];
    temp[i] = JSON.stringify(temp[i]);
  }
  if (map.has(temp[i])) {
    map.set(temp[i], true);
  } else {
    map.set(temp[i], false);
    if (typeof mid === "object") {
      temp[i] = JSON.parse(temp[i]);
    }
    arr.push(temp[i]);
  }
}
console.log(arr);

遇到非基本类型,就JSON.stringfy成字符串 再比较。比较之后