Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicate values from an array of objects in javascript [duplicate]

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

like image 704
user7334203 Avatar asked Aug 01 '17 13:08

user7334203


People also ask

How do you remove duplicate values from an array?

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.

How do you get all unique values remove duplicates in a JavaScript array?

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.

Can array have duplicate values JavaScript?

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.


1 Answers

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);
like image 99
Hassan Imam Avatar answered Oct 12 '22 15:10

Hassan Imam