Remove duplicate values from an array of objects i

2020-01-29 07:22发布

问题:

i have an array of objects like this:

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

This array is composed when my react component is rendered. The i user Array.prototype.unshift for adding a desired element in the top of my array. So i write arr.unshift({label: All, value: All}). When my component first rendered my array is successfully created as i desire. But when i rerender it it shows me the array with the value {label: All, value: All} as duplicate. To be more specific it is shown something like this:

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

How can i fix this? I tried the methods described in a specific topic here but it didn't work

回答1:

You can use array#reduce and array#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);



回答2:

One liner solutions for ES6+

Unique by label and value

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

Unique by all properties of the object:

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


回答3:

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'));