js-challenges icon indicating copy to clipboard operation
js-challenges copied to clipboard

对象去重

Open JeromeD3 opened this issue 1 year ago • 2 comments

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 } } } ]

JeromeD3 avatar May 02 '23 16:05 JeromeD3

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); // 返回唯一对象的值作为去重后的数组 }

mafeiGitHub avatar Aug 10 '23 02:08 mafeiGitHub

/**
 * 对于[{ 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())
}

topulikeweb avatar Mar 29 '24 14:03 topulikeweb