
The lastIndexOf() starts searching the array from the end and stops at the beginning of the array.

As the name suggests, it returns the position of the last occurrence of the items in an array.

JavaScript provides us an alternate array method called lastIndexOf(). Note that if the item is present more than once, the indexOf() method returns the position of the first occurrence. But you can pass in a position as a second argument to skip the starting elements to be included in the search: fruits. const fruits = īy default, the indexOf() method starts searching the given item from the beginning of the array and stops at the end of the array. This method searches the array for the given value and returns its index. The simplest and fastest way to check if an item is present in an array is by using the Array.indexOf() method. The includes() method doesn't work in IE and is only available in modern browsers. includes ( 29n ) // true // Symbolīoth includes() and indexOf() behave differently with NaN ("Not-a-Number") property: const arr = // ✅ includes ( undefined ) // true // boolean includes ( '🍐', 4 ) // trueīeside strings, the includes() method also works great with other primitive types: const symbol = Symbol ( '🌟' ) const types = // strings But you can also pass in a starting index as a second parameter to start the search from a different position: fruits. The includes() method is perfect for finding whether the element exists or not as a simple boolean value: const fruits = īy default, the includes() method searches the entire array. This method returns true if the element exists in the array and false if not. The includes method was added in ES6 to determine whether an array contains a specified value. to check whether the given value or element exists in an array or not. Apart from loops, you can use includes(), indexOf(), find(), etc. One way would be to loop manually over all the objects from the array and check if the object exists.Īnother way would be to use the method (), which returns the object if it exists, or undefined otherwise.In JavaScript, there are multiple ways to check if an array includes an item. It's important to note that there are other ways to accomplish the same task.

Let's take the following phone book as an example: const people = [ Thus, in this article, you will see how to check if an array of objects contains an object with a specific value. Imagine you have an array with people, and you have the same person multiple times. Having duplicate data in your application is not desired.
