- # How to check if array includes a value in JavaScript?
- # Checking for Array of Objects using some()
- # Case Sensitive
- # Browser Support
- # Community Input
- How to Check if an Array Contains a Value in Javascript
- 1) Check if an array contains a string
- 2) Check if an array contains a number
- 3) Check if an array contains an object
- Summary
- JavaScript: Check if Array Contains a Value/Element
- Check Array of Primitive Values Includes a Value
- Array.includes() Function
- Array.indexOf() Function
- Checking if Array of Objects Includes Object
- some() Function
- Free eBook: Git Essentials
- Conclusion
# How to check if array includes a value in JavaScript?
# Checking for Array of Objects using some()
For a more versatile solution that works on other data types, you may want to use some instead.
«.some()»: tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
const array = ['🥗', '🍔', '🍰']; array.some(food => food === '🍰'); // true
This method is ideal for an array of objects.
const array = [ name: 'js' >, name: 'css' >]; array.some(code => code.name === 'js'); // true array.some(code => code.name === '🤖'); // false
In a previous code note, I talked about a quick & dirty way to check objects using JSON.stringify() .
Taking that concept, we can also use it to compare object element in an array like this:
const array = [ name: 'js' >, name: 'css' >]; array.some(code => JSON.stringify(code) === JSON.stringify( name: 'css' >)); // true
# Case Sensitive
Both includes and indexOf are case sensitive:
const array = ['SAMANTHA']; array.includes('samantha'); // false array.indexOf('samantha') !== -1; // false
To make it case insensitive, you could consider changing the case of the array like so:
const array = ['SAMANTHA']; const sameCaseArray = array.map(value => value.toLowerCase()); // ['samantha'] sameCaseArray.includes('samantha'); // true sameCaseArray.indexOf('samantha') !== -1; // true
But if you were using some , you can do it in one line:
const array = ['SAMANTHA']; array.some(value => value.toLowerCase() === 'samantha'); // true
# Browser Support
Support for includes is really good for all modern browsers. However, if you need IE or older browser, you will need to use indexOf .
# Community Input
- @lolinoid: contains >@prvnbist That’s a method DOM Nodes, most known example for it would be getting a list of classnames which will be a node list then you can use contain method to see if it has a classname. Or you can convert it to an array and then use includes method
- You can use the in operator to loop over an object to check if a specific property key exists. (Knowledge shared by @fvbix)
const object = kiwi: '🥝', pear: '🍐', cheese: '🧀' >,; 'kiwi' in object; // true // Use it as a conditional if ('kiwi' in object) // do something if property key exists >
if (~array.indexOf('🍰')) // do something >
- @danvc: ~[].indexOf(value) . The bitwise ~ operator will return a truthy value for anything but -1 . Negating it is as simple as doing !~ .
- @smokku
: Bitwise not gives you the opposite of the number, but we use two’s complement
How to Check if an Array Contains a Value in Javascript
Summary: in this tutorial, you’ll learn how to check if an array contains a value in JavaScript.
A value in JavaScript can be primitive such as a number or string. Or it can be an object.
This tutorial shows you to check if an array contain a value, being a primtive value or object.
1) Check if an array contains a string
To check if an array contains a primitive value, you can use the array method like array.includes()
The following example uses the array.includes() method to check if the colors array contains ‘red’ :
const colors = ['red', 'green', 'blue']; const result = colors.includes('red'); console.log(result); // true
Code language: JavaScript (javascript)
If you want to ingore the letter cases when checking, you can:
- First, return a new array that contains all elements in lowercase using the map() and toLocaleLowerCase() methods.
- Then, use the includes() method to check.
The following example illustrates the steps:
const colors = ['Red', 'GREEN', 'Blue']; const result = colors.map(e => e.toLocaleLowerCase()) .includes('green'); console.log(result); // true
Code language: JavaScript (javascript)
In this example, the colors array doesn’t contain ‘green’ but ‘GREEN’ .
First, the map() method makes every element in the colors array lowercase and returns a new array. Then, the includes() method returns true because the result array contains the element ‘green’ .
2) Check if an array contains a number
The following example shows how to use the includes() method to check if an array contains a number:
const ratings = [1,2,3,4,5]; let result = ratings.includes(4); console.log(result); // true result = ratings.includes(6); console.log(result); // false
Code language: JavaScript (javascript)
3) Check if an array contains an object
The following example uses the includes() method to check if an array contains an object:
const john = < 'name': 'John Doe', 'email': 'john.doe@example.com' >; const jane = < 'name': 'Jane Doe', 'email': 'jane.doe@example.com' >; const list = [john, jane]; let result = list.includes(john); console.log(result); // true
Code language: JavaScript (javascript)
In this example, the list.includes(john) returns true because the list array contains the john object reference.
In practice, instead of searching for a refenrence, you often search for objects by their property values. The following example won’t work:
const list = [< 'name': 'John Doe', 'email': 'john.doe@example.com' >, < 'name': 'Jane Doe', 'email': 'jane.doe@example.com' >]; let result = list.includes(< 'name': 'John Doe', 'email': 'john.doe@example.com' >); console.log(result); // false
Code language: JavaScript (javascript)
In this example, the following object:
< 'name': 'John Doe', 'email': 'john.doe@example.com' >
Code language: JavaScript (javascript)
…looks like the first element in the list array. However, the includes() method returns false because the list doesn’t contain a reference to the searched object.
To check if an array contains an object, you follow these steps:
- First, create a helper function that compares two objects by their properties.
- Second, use the array.some() method to find the searched object by property values.
To compare objects by property values, you use the following helper function:
const isEqual = (first, second) => < return JSON.stringify(first) === JSON.stringify(second); >
Code language: JavaScript (javascript)
The isEqual() function returns true if the first and second objects have the same number of properties with the same values.
And the limitation of the isEqual() function is that the order of properties of the compared objects must be the same.
Note that the some library provides the function that allows you compare two objects by their property values.
For example, Lodash has a _.isEqual() method that allows you to compare objects if they are equal with a better performance than using the JSON.stringify() .
The following uses the array.some() method to match every element of an array with the searched object:
const result = list.some(e => isEqual(e, < 'name': 'John Doe', 'email': 'john.doe@example.com' >)); console.log(result); // true
Code language: JavaScript (javascript)
const list = [< 'name': 'John Doe', 'email': 'john.doe@example.com' >, < 'name': 'Jane Doe', 'email': 'jane.doe@example.com' >]; const isEqual = (first, second) => < return JSON.stringify(first) === JSON.stringify(second); > const result = list.some(e => isEqual(e, < 'name': 'John Doe', 'email': 'john.doe@example.com' >)); console.log(result); // true
Code language: JavaScript (javascript)
Summary
- For primitive values, use the array.includes() method to check if an array contains a value.
- For objects, use the isEqual() helper function to compare objects and array.some() method to check if the array contains the object.
JavaScript: Check if Array Contains a Value/Element
Arrays are one of the most widely used data structures in Computer Science. While dealing with a list of items (array), we are often required to look for a particular value in the list. JavaScript contains a few built-in methods to check whether an array has a specific value, or object.
In this article, we’ll take a look at how to check if an array includes/contains a value or element in JavaScript.
Check Array of Primitive Values Includes a Value
Array.includes() Function
The simplest way to check for a primitive value in an array is to use the includes() method:
let isInArray = arr.includes(valueToFind[, fromIndex]) // 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
For example, let’s check whether the array of animals contains the dog and cat emojis:
let animals = ["🐘", "🐒", "🐶", "🐍"] animals.includes("🐶") // true animals.includes("🐱") // false
The function returns a boolean value, signifying the value’s presence or lack thereof.
Array.indexOf() Function
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 .
For example, we can look for the first occurrence of a grade in an array containing grades:
let grades = ["B", "D", "C", "A"] grades.indexOf("A") // 3 grades.indexOf("F") // -1
In the first instance, the element is present, and its position is returned. In the second instance, the return value signifies that the element is not present.
We can use this to alter code flow easily:
let grades = ["B", "D", "C", "A"] if (grades.indexOf("F") >= 0) < console.log("Element is present"); > else < console.log("Element is not present"); >
If we pass in F , the adequate message is printed:
Checking if Array of Objects Includes Object
some() Function
When searching for an object, includes() checks whether the provided object reference matches the one in the array. This is rarely what we want, because objects can have identical fields with corresponding values but different references.
We can use the some() method to search by object’s contents. The some() method takes one argument and accepts a callback, which is executed once for each value in the array until it finds an element which meets the condition set by the callback function, and returns true .
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Let’s look at some() in action to understand it better:
let animals = [name: "dog">, name: "snake">, name: "monkey">, name: "donkey">] let element = name: "monkey"> animals.some(animal => animal.name === element.name)
The callback function returns false for the first two cases, but returns true for the third element, as the names match. After this, some() halts execution and returns true .
Conclusion
In this article, we’ve gone over the few ways to check whether an array contains a value or not, in JavaScript.
We’ve covered the includes() function, which returns a boolean value if the value is present. The indexOf() function returns the index of a value if it’s present, and -1 if it isn’t.
Finally, for objects, the some() function helps us search for object presence based on their contents.