Check if an array contains any element of another

2019-01-02 19:55发布

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?

22条回答
还给你的自由
2楼-- · 2019-01-02 20:19

Personally, I would use the following function:

var arrayContains = function(array, toMatch) {
    var arrayAsString = array.toString();
    return (arrayAsString.indexOf(','+toMatch+',') >-1);
}

The "toString()" method will always use commas to separate the values. Will only really work with primitive types.

查看更多
浮光初槿花落
3楼-- · 2019-01-02 20:20

You could use lodash and do:

_.intersection(originalTarget, arrayToCheck).length > 0

Set intersection is done on both collections producing an array of identical elements.

查看更多
还给你的自由
4楼-- · 2019-01-02 20:24

I came up with a solution in node using underscore js like this:

var checkRole = _.intersection(['A','B'], ['A','B','C']);
if(!_.isEmpty(checkRole)) { 
     next();
}
查看更多
看风景的人
5楼-- · 2019-01-02 20:24

Array .filter() with a nested call to .find() will return all elements in the first array that are members of the second array. Check the length of the returned array to determine if any of the second array were in the first array.

getCommonItems(firstArray, secondArray) {
  return firstArray.filter((firstArrayItem) => {
    return secondArray.find((secondArrayItem) => {
      return firstArrayItem === secondArrayItem;
    });
  });
}
查看更多
登录 后发表回答