skip to Main Content

I have an array called items which contains a list of strings which I want to search against me key_res array which contains some keywords I need either a true or false value on.

This is the code I have so far which works:

const items = ['Quality 1080p', 'Quality 720p', 'Quality 4K'];
const key_res = ['4K', '6K'];
contains_string = items.every(item => {
            if(key_res.some(string => item.includes(string))) {
                return false;
            }
            return true;
        });

Is there a way I can return a boolean value easier than going through a loop and then setting a boolean?

2

Answers


  1. I’m not sure if this helps, it really doesn’t save a lot of code, but using map instead of forEach will loop and allow you to return a value. So now you only console.log one time

    const items = ['Quality 1080p', 'Quality 720p', 'Quality 4K'];
    const key_res = ['4K', '6K'];
    console.log(items.map(i => key_res.some(s => i.includes(s))));
    Login or Signup to reply.
  2. Use some instead of forEach:

    let items = ['Quality 1080p', 'Quality 720p', 'Quality 4K'];
    const key_res = ['4K', '6K'];
    let bool = items.some(item => key_res.some(string => item.includes(string)));
    console.log(bool);
    
    items = ['Quality 1080p', 'Quality 720p'];
    bool = items.some(item => key_res.some(string => item.includes(string)));
    console.log(bool);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search