Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  186] [ 2]  / answers: 1 / hits: 87093  / 7 Years ago, tue, august 1, 2017, 12:00:00

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


More From » arrays

 Answers
17

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




[#56895] Sunday, July 30, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dylondaytond

Total Points: 92
Total Questions: 88
Total Answers: 96

Location: China
Member since Fri, Jan 15, 2021
3 Years ago
dylondaytond questions
Tue, Jun 22, 21, 00:00, 3 Years ago
Thu, May 7, 20, 00:00, 4 Years ago
;