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
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);
来源:https://stackoverflow.com/questions/45439961/remove-duplicate-values-from-an-array-of-objects-in-javascript