Check if an Element exists in an Array in React

avatar

Borislav Hadzhiev

Last updated: Apr 25, 2022

banner

Photo from Unsplash

Check if an Element exists in an Array in React #

To check if an element exists in an array in React:

  1. Use the includes() method to check if a primitive exists in an array.
  2. Use the some() method to check if an object exists in an array.
App.js
import {useState} from 'react'; const App = () => { const initialEmployees = [ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, ]; const [employees, setEmployees] = useState(initialEmployees); // 👇️ check if array contains object const isFound = employees.some(element => { if (element.id === 1) { return true; } return false; }); if (isFound) { console.log('✅ array contains object with id = 1'); } const [fruits, setFruits] = useState(['apple', 'banana']); // 👇️ check if array contains primitive (string or number) if (fruits.includes('apple')) { console.log('✅ array contains apple'); } return ( <div> {employees.map(employee => { return ( <div key={employee.id}> <h2>id: {employee.id}</h2> <h2>name: {employee.name}</h2> </div> ); })} <hr /> {fruits.map((fruit, index) => { return ( <div key={index}> <h2>{fruit}</h2> </div> ); })} </div> ); }; export default App;

The first example shows how to check if an object exists in an array.

App.js
// 👇️ check if array contains object const isFound = employees.some(element => { if (element.id === 1) { return true; } return false; }); if (isFound) { console.log('✅ array contains object with id = 1'); }

The function we passed to the Array.some method will get called with each value of the array.

If it returns a truthy value at least once, the Array.some method short-circuits and returns true.

In our conditional, we verify if the identifier property of the object is equal to a specific value. If it is, we know that the object exists in the array.

The second example uses the Array.includes method to check if a primitive value (a string) is contained in the array.

App.js
if (fruits.includes('apple')) { console.log('✅ array contains apple'); }

The includes() method returns true if the passed in value is contained in the array and false otherwise.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.