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
We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.
To find a unique array and remove all the duplicates from the array in JavaScript, use the new Set() constructor and pass the array that will return the array with unique values.
To check if an array contains duplicates: Pass the array to the Set constructor and access the size property on the Set . Compare the size of the Set to the array's length. If the Set contains as many values as the array, then the array doesn't contain duplicates.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With