January 26, 2022

Blog @ Munaf Sheikh

Latest news from tech-feeds around the world.

How to check if an array includes a value in JavaScript? Example Tutorial


Actually, there are several ways of check if a value exists in an array in JavaScript and I will show you not one, not two but three ways to perform a check. So what are we waiting for, let’s start?

Firstly, What is an array? In JavaScript, Array is a single variable that is used to store different elements. This means that JavaScript array(s) can hold different types of data like the number, string, boolean and object values at the same time. 

Unlike in Java, arrays in JavaScript are not strongly typed.  It is strongly typed in fact from creation time you would specify what type of data is coming in and its length. And you can’t do otherwise once you have stated the type of data and length. Any attempts to do that lead to compilation error.

Also, the length of an array is dynamically sized and can keep growing. In other words, you don’t need to specify the array size upfront. You can access the values by referring to an index number. The index number starts from zero as you can see from the image below. The first item in the array is index 0, the second item, index 1. the third item, index 2. E.t.c

Checking if an array includes a value means that the value you want to check is passed in as the method you want to use.

How to create an array in JavaScript?

There are different ways to create an array in javaScript but the more preferred and common way to create an array is to use the array literal notation, The array literal form uses the square brackets [] to wrap a comma-separated list of elements. The following example creates the colors array that holds three strings:

  1. let colors = [‘red’, ‘green’, ‘blue’];

You can as well create an empty array for later use by doing the following:

  1. Let my_Array = [];

Array in JavaScript has its own in-built method which you can bank on at any time. You don’t just have to start writing them. All you need is to call the method needed for the task you are doing.

The methods are:

  1. The join() method also joins all array elements into a string.
  2. The pop() method returns the value that was “popped out”
  3. The push() method adds a new element to an array (at the end). When you work with arrays, it is easy to remove elements and add new elements.
  4. The indexOf() method finds the index of an element.
  5. The Array.isArray() method checks if a value is an array, it returns true if the value you are looking for is present, otherwise returns false.
  6. The shift() method removes the first array element and “shifts” all other elements to a lower index and returns the value that was “shifted out”.
  7. The unshift() method adds a new element to an array (at the beginning), and “unshifts” older elements, and returns the new array length.
  8. The splice() method can be used to add new items to an array, specifying what index you want to add the new items too.

The concat() method creates a new array by merging (concatenating) existing arrays, Note that The concat() method does not change the existing arrays. It always returns a new array. The concat() method can take any number of array arguments.

How to check if an array includes a value in JavaSCript

Now, let’s see a couple of code examples of whether a JavaScript array contains a particular value or not. 

1. CODE IMPLEMENTATION 1

  1. const colors = [‘red’, ‘green’, ‘blue’];

  2. const result = colors.includes(‘red’);

  3. console.log(result); // true

The first implementation here is to have an array first and then call the includes method with the value you want to check if it’s in there, and you save it inside the result, the last line prints in the console and it returns true

2. CODE IMPLEMENTATION 2

  1. const colors = [‘Red’, ‘GREEN’, ‘Blue’];

  2. const result = colors.map(e => e.toLocaleLowerCase()).includes(‘green’);

  3. console.log(result); // true

The second implementation is still the same thing first, having an array with values. Then you call on the map method which takes in an anonymous function with parameter e, in our case we are saying that whatever the ‘e’ is, it should be converted to lowercase and the includes method was called on it. The last line prints in the console and it returns true

 

3 CODE IMPLEMENTATION  3 => checks if array contains an object

  1. const john = {

  2. ‘name’: ‘John Doe’,

  3. ’email’: ‘john.doe@example.com’

  4. };

  5. const jane = {

  6. ‘name’: ‘Jane Doe’,

  7. ’email’: ‘jane.doe@example.com’

  8. };

  9. const list = [john, jane];

  10. let result = list.includes(john);

  11. console.log(result); // true

Here, we would be looking at objects. Having the two objects and both keys are put in an array, an array was created with the keys inside, it still includes the method we have been using on it.

 

In practice, instead of searching for a reference, you often search for objects by their property values. The following example won’t work:

  1. const list = [{

  2. ‘name’: ‘John Doe’,

  3. ’email’: ‘john.doe@example.com’

  4. }, {

  5. ‘name’: ‘Jane Doe’,

  6. ’email’: ‘jane.doe@example.com’

  7. }];

  8. let result = list.includes({

  9. ‘name’: ‘John Doe’,

  10. ’email’: ‘john.doe@example.com’

  11. });

  12. console.log(result); // false

That’s all about how to check if an array includes a value in JavaScript or not. We have seen three ways to accomplish this task and the best way is to use the includes() method which checks this for you. If you want ot learn more, you should join a good
JavaScript course and if you need a recommendation you can check out
this list of best JavaScript courses for beginners

Other JavaScript Articles and TutorialsYou May like to
explore

Thanks for reading this article so far.  If you like this JavaScript array
tutorial and how to check if any includes a value in JavaScript then please share it with your friends and colleagues. If you have
any
questions or feedback, then, please drop a comment.

P. S. – If you want to master JavaScript but looking for free resources to learn JavaScript then you can also go through these free JavaScript courses. It has many hands-on free courses to learn modern JavaScript. It
contains the best free Javascript courses from Udemy, Coursera, and
Pluralsight. 



Source link