How do you check if an element is present in an array javascript?

Examples

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Mango");

Try it Yourself »

Start the search at position 3:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Banana", 3);

Try it Yourself »


Definition and Usage

The includes() method returns true if an array contains a specified value.

The includes() method returns false if the value is not found.

The includes() method is case sensitive.


Syntax

array.includes(element, start)

Parameters

Parameter Description
element Required.
The value to search for.
start Optional.
Start position. Default is 0.

Return Value

Type Description
A boolean true if the value is found, otherwise false.

Browser Support

includes() is an ECMAScript7 (ES7) feature.

ES7 (JavaScript 2016) is supported in all modern browsers:

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

includes() is not supported in internet Explorer or Edge 13 (or earlier).



I benchmarked it multiple times on Google Chrome 52, but feel free to copypaste it into any other browser's console.


~ 1500 ms, includes (~ 2700 ms when I used the polyfill)

var array = [0,1,2,3,4,5,6,7,8,9]; 
var result = 0;

var start = new Date().getTime();
for(var i = 0; i < 10000000; i++)
{
  if(array.includes("test") === true){ result++; }
}
console.log(new Date().getTime() - start);

~ 1050 ms, indexOf

var array = [0,1,2,3,4,5,6,7,8,9]; 
var result = 0;

var start = new Date().getTime();
for(var i = 0; i < 10000000; i++)
{
  if(array.indexOf("test") > -1){ result++; }
}
console.log(new Date().getTime() - start);

~ 650 ms, custom function

function inArray(target, array)
{

/* Caching array.length doesn't increase the performance of the for loop on V8 (and probably on most of other major engines) */

  for(var i = 0; i < array.length; i++) 
  {
    if(array[i] === target)
    {
      return true;
    }
  }

  return false; 
}

var array = [0,1,2,3,4,5,6,7,8,9]; 
var result = 0;

var start = new Date().getTime();
for(var i = 0; i < 10000000; i++)
{
  if(inArray("test", array) === true){ result++; }
}
console.log(new Date().getTime() - start);

Topic: JavaScript / jQueryPrev|Next

Answer: Use the indexOf() Method

You can use the indexOf() method to check whether a given value or element exists in an array or not. The indexOf() method returns the index of the element inside the array if it is found, and returns -1 if it not found. Let's take a look at the following example:

ES6 has introduced the includes() method to perform this task very easily. But, this method returns only true or false instead of index number, as you can see here:

All modern browsers supports the includes() method and it is preferred for modern applications.

Please check out the tutorial on JavaScript Arrays to learn more about the arrays.


Here are some more FAQ related to this topic:

  • How to remove duplicate values from a JavaScript array
  • How to remove a specific item from an array in JavaScript
  • How to loop through an array in JavaScript

In JavaScript, there are multiple ways to check if an array includes an item. You can always use the for loop or Array.indexOf() method, but ES6 has added plenty of more useful methods to search through an array and find what you are looking for with ease.

indexOf() Method

The simplest and fastest way to check if an item is present in an array is by using the Array.indexOf() method. This method searches the array for the given item and returns its index. If no item is found, it returns -1.

const fruits = ['🍎', '🍋', '🍊', '🍇', '🍍', '🍐'];

fruits.indexOf('🍋'); // 1  (true)
fruits.indexOf('🍍'); // 4  (true)
fruits.indexOf('🍌'); // -1 (false)

By default, the indexOf() method starts searching from the beginning of the array, and stops at the end of the array. But you can pass in a position as a second argument to skip the starting elements to be included in the search:

fruits.indexOf('🍋', 1); // 1    (true)
fruits.indexOf('🍋', 4); // -1   (false)

Note that if the item is present more than once, the indexOf() method returns the position of the first occurrence.

JavaScript provides us an alternate array method called lastIndexOf(). As the name suggests, it returns the position of the last occurrence of the items in an array. The lastIndexOf() starts searching the array from the end and stops at the beginning of the array. You can also specify a second parameter to exclude items at the end.

const fruits = ['🍎', '🍋', '🍊', '🍇', '🍍', '🍐'];

fruits.lastIndexOf('🍇');       // 3   (true)
fruits.lastIndexOf('🍉');       // -1  (true)
fruits.lastIndexOf('🍋', 4);    // 1   (false)

Both indexOf() and lastIndexOf() perform a case-sensitive search and work in all browsers, including IE9 and up.

includes() Method

The includes method is part of ES6 that can also be used to determine whether an array contains a specified item. This method returns true if the element exists in the array, and false if not. The includes() method is perfect for finding whether the element exists or not as a simple boolean value.

const fruits = ['🍎', '🍋', '🍊', '🍇', '🍍', '🍐'];

fruits.includes('🍇');  // true
fruits.includes('🍉');  // false

By default, the includes() method searches the entire array. But you can also pass in a starting index as a second parameter to start the search from a different position:

fruits.includes('🍐', 4);    // true
fruits.includes('🍊', 4);    // false

Beside strings, the includes() method also works great with other primitive types:

const symbol = Symbol('🌟');

const types = ['Apple', 150, null, undefined, true, 29n, symbol];

// strings
types.includes('Apple');    // true

// numbers
types.includes(150);        // true

// null
types.includes(null);       // true

// undefined
types.includes(undefined);  // true

// boolean
types.includes(true);       // true

// BigInt
types.includes(29n);        // true

// Symbol
types.includes(symbol);     // true

Both includes() and indexOf() behave differently with NaN ("Not-a-Number") property:

const arr = [NaN];

// ✅
arr.includes(NaN) // true

// ❌
arr.indexOf(NaN)   // -1

The incudes() method doesn't work in IE and is only available in modern browsers.

find() Method

Unlike includes(), the find() method executes the specified function for each element present in the array. It returns the value of the first element in an array that passes a certain condition:

const fruits = ['🍎', '🍋', '🍊', '🍇', '🍍', '🍐'];

const value = fruits.find(elem => elem === '🍍');

console.log(value); // 🍍

Note: In the above example, I have used an arrow function to loop over elements. Arrow functions are part of ES6 and if you don't know about them, take a look at this article.

If no element is found where the function returns true, the find() method returns an undefined value:

const value = fruits.find(elem => elem === '🍉');

console.log(value); // undefined

You can also get the index of the current element as the second parameter of the function. This is useful when you want to compare the index too:

fruits.find((elem, idx) => elem === '🍇' && idx > 2); // 🍇

fruits.find((elem, idx) => elem === '🍋' && idx > 2); // undefined

Another benefit of the find() method is that it works for other data types like objects as well:

const animals = [{ name: '🐱' }, { name: '🐒' }, { whale: '🐋' }];

const found = animals.find(elem => elem.name === '🐒');

console.log(found); // { name: '🐒' }

The find() method only works in modern browsers.

some() Method

The some() method works quite similar to the find() except that it returns a boolean value true if the element is found in the array, otherwise false.

const fruits = ['🍎', '🍋', '🍊', '🍇', '🍍', '🍐'];

fruits.some(elem => elem === '🍐');     // true
fruits.some(elem => elem === '🍓');     // false

The some() method can also be used with an array an objects:

const animals = [{ name: '🐱' }, { name: '🐒' }, { whale: '🐋' }];

animals.some(elem => elem.name === '🐒');   // true
animals.some(elem => elem.name === '🍊');   // false

You can use the some() method in all modern browsers, and in IE9 and above.

every() Method

The every() method is like some() except that it makes sure that all elements in the array pass a certain condition:

const numbers = [10, 99, 75, 45, 33];

// check if all elements are > 15
const result = numbers.every(num => num > 15);

console.log(result); // false

Just like some(), the every() works in all modern browsers, and IE9 and higher.

Both indexOf() and includes() methods are case-sensitive. This means that you must specify the same case string to search the array:

const names = ['Ali', 'Atta', 'Alex', 'John'];

names.indexOf('atta');   // -1
names.includes('atta');  // false

To perform a case-insensitive search, one way is to convert each string in the array to lowercase by using the map() method and then perform the search:

const names = ['Ali', 'Atta', 'Alex', 'John'];

names.map(elem => elem.toLowerCase()).indexOf('atta');   // 1
names.map(elem => elem.toLowerCase()).includes('atta');  // true

Alternatively, you could use the some() method to do both string lowercase and comparison in one step:

names.some(elem => elem.toLowerCase() === 'atta');   // true

Conclusion

In this article, we looked at 5 different JavaScript Array's methods to check if an item exists in an array.

A legitimate question you may ask, why do we need all these methods in the first place? Why not have just one method to search through an array?

A simple answer would be that all these methods are intended for different use cases:

  • Want to know the element position in the array? Use the indexOf() method.
  • Want to find the position of the last occurrence of an element? There is a lastIndexOf() method available for this purpose.
  • Do you only want to know if the element exists or not? Use the includes() method.
  • Do you want to get the matching element too? Use the find() method.
  • Working with an array of objects? Use the some() method to check the existence of the matching element.
  • Want to perform a case-insensitive search? Use find() or some() method.
  • Want to check if all elements in an array satisfy a certain condition? Use the every() method.
  • And so on.

To learn more about JavaScript arrays and how to use them to store multiple pieces of information in one single variable, take a look at this article.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

How do you check if an array contains an element?

indexOf() Method The simplest and fastest way to check if an item is present in an array is by using the Array. indexOf() method. This method searches the array for the given item and returns its index. If no item is found, it returns -1.

How do you find something in an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.

How do you check if an array does not contain a value JavaScript?

To check if an array doesn't include a value, use the logical NOT (!) operator to negate the call to the includes() method. The NOT (!) operator returns false when called on a true value and vice versa.

How do you check if an array contains a number in JavaScript?

To check if an array contains only numbers: Use the Array. every() method to iterate over the array. On each iteration, check if the type of the current element is number . The every method will return true if the array contains only numbers and false otherwise.