Check if an array contains any element of another array in JavaScript

后端 未结 26 1150
礼貌的吻别
礼貌的吻别 2020-11-22 08:48

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:

26条回答
  •  旧时难觅i
    2020-11-22 09:16

    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.

提交回复
热议问题