

We can use the some() method to search by object's contents. This is rarely what we want, because objects can have identical fields with corresponding values but different references. When searching for an object, includes() checks whether the provided object reference matches the one in the array. If we pass in F, the adequate message is printed: Element is not presentĬhecking if Array of Objects Includes Object some() Function We can use this to alter code flow easily: let grades = In the second instance, the return value signifies that the element is not present. In the first instance, the element is present, and its position is returned. In cases where we need the exact location of the element we're looking for, we can use the indexOf(elem) method, which looks for elem in the specified array and returns the index of its first occurrence, and -1 if the array does not contain elem.įor example, we can look for the first occurrence of a grade in an array containing grades: let grades = The function returns a boolean value, signifying the value's presence or lack thereof. arr - array we're inspecting // valueToFind - value we're looking for // fromIndex - index from which the search will start (defaults to 0 if left out) // isInArray - boolean value which tells us if array contains valueToFindįor example, let's check whether the array of animals contains the dog and cat emojis: let animals = The simplest way to check for a primitive value in an array is to use the includes() method: let isInArray = arr.includes(valueToFind) Check Array of Primitive Values Includes a Value Array.includes() Function


In this article, we'll take a look at how to check if an array includes/contains a value or element in JavaScript. JavaScript contains a few built-in methods to check whether an array has a specific value, or object. While dealing with a list of items (array), we are often required to look for a particular value in the list. Arrays are one of the most widely used data structures in Computer Science.
