964

I have a target array ["apple","banana","orange"], and I want to check if other arrays contain any one of the target array elements.

For example:

["apple","grape"] //returns true;

["apple","banana","pineapple"] //returns true;

["grape", "pineapple"] //returns false;

How can I do it in JavaScript?

4
  • 5
    Use a for loop and iterate over the target array. If every element is contained within the current array (use current.indexOf(elem) !== -1), then they're all in there. Commented May 1, 2013 at 3:59
  • 4
    @LeonGaban I disagree. I wouldn't import a library just to perform this operation. Commented May 8, 2020 at 6:40
  • 3
    @devpato yeah changed my mind, the ES6 solution is my fav Commented May 12, 2020 at 19:31
  • Just in case if you want to get the elements rather than just true or false then you need to use .filter() :: Javascript algorithm to find elements in array that are not in another array Commented Jul 9, 2020 at 14:52

32 Answers 32

1
2
0
var target = ["apple","banana","orange"];
var checkArray = ["apple","banana","pineapple"];

var containsOneCommonItem = target.some(x => checkArray.some(y => y === x));`

["apple","grape"] //returns true;

["apple","banana","pineapple"] //returns true;

["grape", "pineapple"] //returns false;
Sign up to request clarification or add additional context in comments.

1 Comment

This solution has already been presented by @bingles
-2

you can do something like this

let filteredArray = array.filter((elm) => {
   for (let i=0; i<anotherAray.length; i++) {
      return elm.includes(anotherArray[i])
    }
  })

1 Comment

Please see Does return stop a loop?. This only checks the first item.
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.