Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

对象去重 #496

Open
JeromeD3 opened this issue May 2, 2023 · 2 comments
Open

对象去重 #496

JeromeD3 opened this issue May 2, 2023 · 2 comments

Comments

@JeromeD3
Copy link

JeromeD3 commented May 2, 2023

const arr = [{ a: 2 }, { a: 2 }, { a: 2, b: 1 }, { a: { b: 1, c: { a: 1 } } }, { a: { b: 1, c: { a: 1 } } }]


// want to get [ { a: 2 }, { a: 2, b: 1 }, { a: { b: 1, c: {a:1 } } } ]
@mafeiGitHub
Copy link

function removeDuplicates(arr) {
var result = {}; // 用于存储唯一对象的空对象
for (var i = 0; i < arr.length; i++) {
var objKey = JSON.stringify(arr[i]); // 将对象转换为字符串作为键
if (!result[objKey]) {//如果该键的值为空
result[objKey] = arr[i]; // 将对象添加到新的对象中作为该键的值
}
}
return Object.values(result); // 返回唯一对象的值作为去重后的数组
}

@topulikeweb
Copy link

topulikeweb commented Mar 29, 2024

/**
 * 对于[{ a: 2 }, { a: 2 }, { a: 2, b: 1 }, { a: { c: { a: 1 },b: 1 } }, { a: { b: 1, c: { a: 1 } } }]进行去重
 */
// 对数组进行规范化,防止因顺序不同导致判别不正确
function equalObj (obj) {
  let res = {}
  const keys = Object.keys(obj).sort()
  for (const item of keys) {
    res[item] = obj[item]
  }
  return res
}

function duplicateRemoval (arr) {
  const map = new Map()
  for (const item of arr) {
    const _obj = JSON.stringify(equalObj(item))
    if (!map.get(_obj)) {
      map.set(_obj, JSON.parse(_obj))
    }
  }
  return Array.from(map.values())
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants