JavaScript数组对象中仅过滤唯一值

7

我有一个对象数组,想要筛选出唯一的样式并且不重复。

const arrayOfObj = [ {name:'a' , style:'p'} , {name:'b' , style:'q'} , {name:'c' , style:'q'}]

result expected : [ {name:'a' , style:'p'}]

6个回答

3
这里提供的解决方案的时间复杂度为O(n)。您可以迭代所有条目来跟踪每个条目出现的次数。然后使用filter()函数过滤只出现一次的条目。

const arrayOfObj = [
  { name: "a", style: "p" },
  { name: "b", style: "q" },
  { name: "c", style: "q" },
]

const styleCount = {}

arrayOfObj.forEach((obj) => {
  styleCount[obj.style] = (styleCount[obj.style] || 0) + 1
})

const res = arrayOfObj.filter((obj) => styleCount[obj.style] === 1)

console.log(res)


似乎这个失去了 "name": "c"。 - VikR

3

根据您的性能/可读性需求之一可能的解决方案是:

arrayOfObj.filter(a => arrayOfObj.filter(obj => obj.style === a.style).length === 1)

1
使用splice方法来查找并删除现有项。

const arrayOfObj = [{
  name: 'a',
  style: 'p'
}, {
  name: 'b',
  style: 'q'
}, {
  name: 'c',
  style: 'q'
}]

const result = arrayOfObj.reduce((acc, x) => {
  const index = acc.findIndex(y => y.style === x.style);
  if (index >= 0) {
    acc.splice(index, 1);
  } else {
    acc.push(x);
  }
  return acc;

}, [])

console.log(result)


1
你需要将它减少。检查数组中是否已经存在具有相同样式的元素,并将其从累加器中移除,否则将其推送到累加器中。

const arr = [
  { name: "a", style: "p" },
  { name: "b", style: "q" },
  { name: "c", style: "q" }
];

  let result = arr.reduce((a,v) => {
     let i = a.findIndex(el => el.style === v.style);
     if(i !== -1) {
        a.splice(i,1);
        return a;
     }
     a.push(v)
     return a;
  },[])

console.log(result);


1
这是一个O(n)时间复杂度的解决方案。您可以遍历所有条目以跟踪每个条目出现的次数。然后使用filter()函数过滤只出现一次的条目。

const arrayOfObj = [ {name:'a' , style:'p'} , {name:'b' , style:'q'} , {name:'c' , style:'q'}];

let count = {};

arrayOfObj.forEach(({style}) => {
    count[style] = (count[style] || 0) + 1;
});

let result = arrayOfObj.filter(({style}) => count[style] === 1);
console.log(result);


1
如果您正在使用lodash库,也可以使用一行代码来实现(uniqBy(array, iteratee))。
const arr = [
  { name: "a", style: "p" },
  { name: "b", style: "q" },
  { name: "c", style: "q" }
];
let result = _.uniqBy(arrayOfObj,'style')
console.log(result)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接