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:10

It can be done by simply iterating across the main array and check whether other array contains any of the target element or not.

Try this:

function Check(A) {
    var myarr = ["apple", "banana", "orange"];
    var i, j;
    var totalmatches = 0;
    for (i = 0; i < myarr.length; i++) {
        for (j = 0; j < A.length; ++j) {
            if (myarr[i] == A[j]) {

                totalmatches++;

            }

        }
    }
    if (totalmatches > 0) {
        return true;
    } else {
        return false;
    }
}
var fruits1 = new Array("apple", "grape");
alert(Check(fruits1));

var fruits2 = new Array("apple", "banana", "pineapple");
alert(Check(fruits2));

var fruits3 = new Array("grape", "pineapple");
alert(Check(fruits3));

DEMO at JSFIDDLE

查看更多
刘海飞了
3楼-- · 2019-01-02 20:14

ES6 (fastest)

const a = ['a', 'b', 'c'];
const b = ['c', 'a', 'd'];
a.some(v=> b.indexOf(v) !== -1)

ES2016

const a = ['a', 'b', 'c'];
const b = ['c', 'a', 'd'];
a.some(v => b.includes(v));

Underscore

const a = ['a', 'b', 'c'];
const b = ['c', 'a', 'd'];
_.intersection(a, b)

DEMO: https://jsfiddle.net/r257wuv5/

jsPerf: https://jsperf.com/array-contains-any-element-of-another-array

查看更多
时光乱了年华
4楼-- · 2019-01-02 20:14

I found this short and sweet syntax to match all or some elements between two arrays. For example

// OR operation. find if any of array2 elements exists in array1. This will return as soon as there is a first match as some method breaks when function returns TRUE

let array1 = ['a', 'b', 'c', 'd', 'e'], array2 = ['a', 'b'];

console.log(array2.some(ele => array1.includes(ele)));

// prints TRUE

// AND operation. find if all of array2 elements exists in array1. This will return as soon as there is a no first match as some method breaks when function returns TRUE

let array1 = ['a', 'b', 'c', 'd', 'e'], array2 = ['a', 'x'];

console.log(!array2.some(ele => !array1.includes(ele)));

// prints FALSE

Hope that helps someone in future!

查看更多
步步皆殇っ
5楼-- · 2019-01-02 20:15

If you're not opposed to using a libray, http://underscorejs.org/ has an intersection method, which can simplify this:

var _ = require('underscore');

var target = [ 'apple', 'orange', 'banana'];
var fruit2 = [ 'apple', 'orange', 'mango'];
var fruit3 = [ 'mango', 'lemon', 'pineapple'];
var fruit4 = [ 'orange', 'lemon', 'grapes'];

console.log(_.intersection(target, fruit2)); //returns [apple, orange]
console.log(_.intersection(target, fruit3)); //returns []
console.log(_.intersection(target, fruit4)); //returns [orange]

The intersection function will return a new array with the items that it matched and if not matches it returns empty array.

查看更多
弹指情弦暗扣
6楼-- · 2019-01-02 20:17

My solution applies Array.prototype.some() and Array.prototype.includes() array helpers which do their job pretty efficient as well

ES6

const originalFruits = ["apple","banana","orange"];

const fruits1 = ["apple","banana","pineapple"];

const fruits2 = ["grape", "pineapple"];

const commonFruits = (myFruitsArr, otherFruitsArr) => {
  return myFruitsArr.some(fruit => otherFruitsArr.includes(fruit))
}
console.log(commonFruits(originalFruits, fruits1)) //returns true;
console.log(commonFruits(originalFruits, fruits2)) //returns false;

查看更多
爱死公子算了
7楼-- · 2019-01-02 20:18

Vanilla JS - single line

ES2016:

let found = arr1.some(r=> arr2.includes(r))

ES6:

let found = arr1.some(r=> arr2.indexOf(r) >= 0)

How it works

some(..) checks each element of the array against a test function and returns true if any element of the array passes the test function, otherwise, it returns false. indexOf(..) >= 0 and includes(..) both return true if the given argument is present in the array.

查看更多
登录 后发表回答