从javascript中的对象数组中删除重复值

时间:2017-08-01 13:58:44

标签: javascript arrays duplicates

我有一个像这样的对象数组:

arr = [
    {label: Alex, value: Ninja},
    {label: Bill, value: Op},
    {label: Cill, value: iopop}
]

此数组在渲染我的react组件时组成。 i用户Array.prototype.unshift用于在数组顶部添加所需元素。 所以我写arr.unshift({label: All, value: All})。当我的组件首次渲染时,我的数组成功创建了我想要的。但是当我重新渲染它时,它会向我显示值为{label: All, value: All}的数组。更具体地说,它显示如下:

arr = [
    {label: All, value: All},
    {label: All, value: All},
    {label: Alex, value: Ninja},
    {label: Bill, value: Op},
    {label: Cill, value: iopop}
]

我该如何解决这个问题?我在这里尝试了特定主题中描述的方法,但它没有工作

6 个答案:

答案 0 :(得分:15)

您可以使用array#reducearray#some

const arr = [
    {label: 'All', value: 'All'},
    {label: 'All', value: 'All'},
    {label: 'Alex', value: 'Ninja'},
    {label: 'Bill', value: 'Op'},
    {label: 'Cill', value: 'iopop'}
]

var result = arr.reduce((unique, o) => {
    if(!unique.some(obj => obj.label === o.label && obj.value === o.value)) {
      unique.push(o);
    }
    return unique;
},[]);
console.log(result);

答案 1 :(得分:2)

这段代码对我有用,

const addresses = [...]; // Some array I got from async call

const uniqueAddresses = Array.from(new Set(addresses.map(a => a.id)))
 .map(id => {
   return addresses.find(a => a.id === id)
 })

答案 2 :(得分:1)

一种适用于ES6 +的班轮解决方案

labelvalue唯一

arr.filter((v,i,a)=>a.findIndex(t=>(t.label === v.label && t.value===v.value))===i)

对象的所有属性唯一:

arr.filter((v,i,a)=>a.findIndex(t=>(JSON.stringify(t) === JSON.stringify(v)))===i)

答案 3 :(得分:0)

const things = {
  thing: [
    { id: '12345', name: 'First name' },
    { id: '12345', name: 'Second name' },
    { id: '34536', name: 'Third name' }, 
  ],
};

const RemoveDuplicates = (array, key) => {
  return array.reduce((arr, item) => {
    const removed = arr.filter(i => i[key] !== item[key]);
    return [...removed, item];
  }, []);
};

console.log(RemoveDuplicates(things.thing, 'id'));

答案 4 :(得分:0)

function removeDuplicates(array, key) {
   let lookup = {};
   array.forEach(element => {
     lookup[element[key]] = element
   });
   return Object.keys(lookup).map(key => lookup[key]);
};

removeDuplicates(array,'objectKey');

答案 5 :(得分:0)

与ES1兼容:

(code that sets up parameters)

相关问题