Skip to content
Advertisement

Check if arrays contain shared elements regardless of index

I’d like to check if two arrays share elements regardless of order.

Given

JavaScript

Will return matches for ‘hello’, ‘how’, and ‘are’

There seems to be something for PHP, array_intersect() (Check if array contains elements having elements of another array), but nothing for JavaScript.

I would use in if the values were in an object, but they are not:

JavaScript

I could also do array.sort() to both arrays, but it’s not guaranteed that both arrays will have same number of values. Therefore even if they are sorted, the compared indices would be off anyway.

How can I do this in JavaScript?

Advertisement

Answer

You can use filter to check if the same element is present in the other array.

JavaScript

You can also define this function on Array prototype

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement