search ]

Check if a Value exists in an Array using JS or jQuery

I’ve already written a post in the past discussing arrays in JavaScript that explains the basic usage of JavaScript arrays. In this post, we’ll specifically talk about how to check if an array contains a specific value or not.

Both JavaScript and jQuery come with built-in methods that return the position of a value in an array.

Using JavaScript Loop to Find an Item in an Array

An old-fashioned way to find a value in a specific array is to use a for loop. This is the most convenient loop type when we want to perform iteration over an array. Take a look at the following example:

let moviesList = ['The Godfather','Forrest Gump','The Matrix','Inception','Catch Me If You Can','Pulp Fiction'];
 
function findValueInArray(value, arr){
  let result = "Doesn't exist";
 
  for(let i=0; i<arr.length; i++){
    let name = arr[i];
    if(name == value){
      result = 'Exist';
      break;
    }
  }
  return result;
}
findValueInArray('Pulp Fiction', moviesList);
// Result : Exist
findValueInArray('Avenger', moviesList);
// Result : Doesn't exist

As mentioned, this is an old-fashioned way to find an item in an array. Now let’s see how to do it more easily using the same built-in methods that come with JavaScript and jQuery.

Using Array.indexOf()

The method Array.indexOf() in JavaScript helps us find an item in an array. If the “item” is found in the array, the method will return the index position of the item, and if the item does not exist, it will return ‘-1‘.

This method works for both arrays and strings.

Syntax

array-or-string.indexOf()

Here’s an example in action:

let moviesList = ['The Godfather','Forrest Gump','The Matrix','Inception','Catch Me If You Can','Pulp Fiction'];
let string = "Catch Me If You Can";
// Find in Array
moviesList.indexOf('Pulp Fiction');
// Result: 5
moviesList.indexOf('The Nun');
// Result: -1
// Find in String
string.indexOf('M');
// Result: 6

Using jQuery.inArray()

The method jQuery.inArray() works identically. It will return the index position if it finds the value we’re looking for, and alternatively, it will return ‘-1‘ if the value is not found in the array.

This method also works for both arrays and strings.

Syntax

jQuery.inArray(value, array [, fromIndex ])

Here’s an example in action:

<html lang="en">
<head>
<!--    Include jQuery Here to test... -->
</head>
<body>

<div>"John" found at <span></span></div>
<div>4 found at <span></span></div>
<div>"Karl" not found, so <span></span></div>
<div>"Pete" is in the array, but not at or after index 2, so <span></span></div>

<script>
    let arr = [4, "Pete", 8, "John"];
    let $spans = $("span");
    $spans.eq(0).text(jQuery.inArray("John", arr));
    $spans.eq(1).text(jQuery.inArray(4, arr));
    $spans.eq(2).text(jQuery.inArray("Karl", arr));
    $spans.eq(3).text(jQuery.inArray("Pete", arr, 2));
</script>

</body>
</html>

When this code runs, the output will be as follows:

// Result: "John" found at 3
// Result: 4 found at 0
// Result: "Karl" not found, so -1
// Result: "Pete" is in the array, but not at or after index 2, so -1

Using the includes() function

Additional simple method to check if a value exists in an array is using the Array.includes() function. The includes() method of Array instances determines whether an array includes a certain value among its entries, returning true or false as appropriate.

This method as well works for both arrays and strings.

Syntax

array.includes(valueToFind[, fromIndex])

Here’s a working example:

// Define an array
const array = [1, 2, 3, 4, 5];

// Check if a value exists in the array
const value = 3;
if (array.includes(value)) {
    console.log(`${value} exists in the array.`);
} else {
    console.log(`${value} does not exist in the array.`);
}

In this example, array.includes(value) will return true if the value 3 exists in the array, otherwise it will return false. You can replace value with any value you want to check for existence in the array.

That’s it. It’s worth noting that this post was mostly translated from a post that does not exist online anymore.

0 Comments...

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development