Get elements that occur in both arrays
11 March 2022 (Updated 12 March 2022)
You want a function that takes two arrays and returns an array containing only the elements that occur in both:
const arr1 = [2, 4, 6, 8]
const arr2 = [2, 10, 6, 15]
console.log(sharedElements) // [2, 6]
Here’s how:
const sharedElements = arr1.filter(arr1Element => {
return arr2.includes(arr1Element)
})
Tagged:
Snippets
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment