0

How to compare values and put all the common elements between the 2 arrays without duplicates values (result expected [8,12])

(Code of the two arrays inserted) https://code.sololearn.com/WrfSEjWTZMgg/?ref=app

8th Jul 2020, 12:05 PM
Adrien Linares
Adrien Linares - avatar
2 Antworten
+ 2
It looks from your expected output that you want the intersection of the two arrays, meaning only values that are present in both arrays. This would result in an array of [8, 12, 8] of which you'd then need to remove duplicate values, which can be done converting the array to a Set. This code will do that and then convert back to an array resulting in [8, 12] let arr3 = [...(new Set(arr1.filter(x => arr2.includes(x))))]; console.log(arr3); // outputs 8, 12
8th Jul 2020, 1:20 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
Set is better for non-duplicate values. Scroll to the basic operations part. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
8th Jul 2020, 12:11 PM
Arnesh
Arnesh - avatar