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

后端 未结 26 1094
礼貌的吻别
礼貌的吻别 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条回答
  • 2020-11-22 09:16

    Vanilla JS

    ES2016:

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

    ES6:

    const 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题