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

后端 未结 26 1512
礼貌的吻别
礼貌的吻别 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 08:56

    Here is an interesting case I thought I should share.

    Let's say that you have an array of objects and an array of selected filters.

    let arr = [
      { id: 'x', tags: ['foo'] },
      { id: 'y', tags: ['foo', 'bar'] },
      { id: 'z', tags: ['baz'] }
    ];
    
    const filters = ['foo'];
    

    To apply the selected filters to this structure we can

    if (filters.length > 0)
      arr = arr.filter(obj =>
        obj.tags.some(tag => filters.includes(tag))
      );
    
    // [
    //   { id: 'x', tags: ['foo'] },
    //   { id: 'y', tags: ['foo', 'bar'] }
    // ]
    

提交回复
热议问题