skip to Main Content

Suppose a given string exists, s="abc"
Is there any way to check if that given string exists in an array, such as,

arr=["pnq","dwksnn","inabcpi","poals"]

Any method/way to see so that a condition will return true in such a case?

5

Answers


  1. you need to search over each array element and check if the given string is contained within any of the elements, you can use the some() method. Here’s the JavaScript code:

    const s = "abc";
    const arr = ["pnq", "dwksnn", "inabcpi", "poals"];
    
    const is_exists = arr.some(element => element.includes(s));
    console.log(is_exists); // true if exists, otherwise false
    
    Login or Signup to reply.
  2. Something like this? using the .includes()?

    const arr=["pnq","dwksnn","inabcpi","poals"]
    function check_presence(elem) {
        return arr.includes(elem)
    }
    console.log(check_presence("pnh"))
    
    Login or Signup to reply.
  3. Simple, you need to iterate over the given array and check if this string exists in each of the strings within the array.

    const arr = ['pnq', 'dwksnn', 'inabcpi', 'poals'];
    const stringToFind = 'abc';
    const doesStringExist = arr.find(item => item.includes(stringToFind));
    
    // OR if you don't want to know which string the given string is a part of, you could use `Array.prototype.some`
    
    const doesStringExist = arr.some(item => item.includes(stringToFind));
    
    console.log(`The string ${stringToFind} ${doesStringExist ? 'Exists' : 'Doesn't Exist'}`);
    
    Login or Signup to reply.
  4. You can use the array method some, and the string method includes.

    const arr = ['pnq', 'dwksnn', 'inabcpi', 'poals'];
    
    // Return true if the array has an element that
    // includes the query string, otherwise false
    function finder(arr, query) {
      return arr.some(el => el.includes(query));
    }
    
    console.log(finder(arr, 'abc'));
    console.log(finder(arr, 'abcd'));
    console.log(finder(arr, '123'));
    console.log(finder(arr, 'pnq'));
    console.log(finder(arr, 'oal'));
    Login or Signup to reply.
  5. we can use the includes() method to check.

    var arr=["pnq","dwksnn","inabcpi","poals"];
    
    console.log(arr.indexOf("pnq") > -1)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search