DEV Community

loading...

Discussion on: We have 2 arrays of objects of the same class. How to substract the 1st from the 2nd, based only on one property?

Collapse
ankit199 profile image
Ankit kumar shukla

Merge both aaray using
Let newSet=[...set1,...set2]
Then apply this funtiin...
function unique(array, propertyName) {
return array.filter((e, i) => array.findIndex(a => a[propertyName] === e[propertyName]) === i);
}

Collapse
axelledrouge profile image
AxelleDRouge Author • Edited

Thanks for your reply.
Could you details more the process you use? Why would you use findIndex?
I tried to use your method in my use case, but it doesn't remove all the values from the smaller list in the total one
I will edit my post to make it more clearer with the expected result

Collapse
ankit199 profile image
Ankit kumar shukla

I have used findindex to find current index property value to match with passed property to make it unique

Thread Thread
axelledrouge profile image
AxelleDRouge Author

Doesn't findIndex returns the first value that match the provided testing function? In need all the elements that match the predicate, not only the first one.

Thread Thread
refschool profile image
Webdeveloper⭐⭐

a more concise way would be to use the new ES6 spread operator and Set
merge your 2 arrays then
let mergedArray = array1.concat(array2)
const unique = [...new Set(mergedArray.map(item => item.label))];