Solution

To check string exists in an array in react js, use the includes() method for an array of string, or number and the findIndex() method for an array of objects.

Snippet

In this snippet, we will see the implementation of the includes() and findIndex() methods.

Check string exists in an array of string, numbers, and boolean.

const arr = ["aGuideHub", "SortoutCode", "Infinitbility"];

arr.includes('aGuideHub'); // true
arr.includes('Hello');  // false

Check string exists in an array of objects

const arr = [
  {
    id: 1,
    name: "aGuideHub"
  },
  {
    id: 2,
    name: "SortoutCode"
  },
  {
    id: 3,
    name: "Infinitbility"
  },
]

let index = arr.findIndex((e) => e.name == 'SortoutCode' )
if(index >= 0){
  console.log("Found", arr[index])
} else {
  console.log("Not Found")
}

Example

In this example, we will create an array and function which check string exits in an array or not.

Let’s start coding…

App.js

import React, { useEffect, useState } from "react";
export default function App() {
  const [domainsList, setDomainsList] = useState([
    "aGuideHub",
    "SortoutCode",
    "Infinitbility"
  ]);
  const [domains, setDomains] = useState([
    {
      id: 1,
      name: "aGuideHub"
    },
    {
      id: 2,
      name: "SortoutCode"
    },
    {
      id: 3,
      name: "Infinitbility"
    }
  ]);

  const checkInDomainsList = (param) => {
    return domainsList.includes(param);
  };

  const checkInDomains = (param) => {
    let index = domains.findIndex((e) => e.name == param);
    if (index >= 0) {
      return true;
    } else {
      return false;
    }
  };

  return (
    <div className="App">
      <h1>{`Check In Array`}</h1>
      <p>{`is array contain aGuideHub: ${checkInDomainsList("aGuideHub")}`}</p>
      <p>{`is array contain Hello: ${checkInDomainsList("Hello")}`}</p>

      <h1>{`Check In Array of object`}</h1>
      <p>{`is Array of object contain aGuideHub: ${checkInDomains(
        "aGuideHub"
      )}`}</p>
      <p>{`is Array of object contain Hello: ${checkInDomains("Hello")}`}</p>
    </div>
  );
}

Output

Check,string,exists,array

codesandbox