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

后端 未结 26 1101
礼貌的吻别
礼貌的吻别 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:09

    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

提交回复
热议问题