How to Check If a Value Exists in Array in JavaScript

    Mar 05, 2020       by Pankaj Kumar

In this article, We will see the different ways to find if a value exists in an array.

1. Using Array.indexOf()

With the help of the above function, we can easily find out the position of the specified value in the array. It mainly returns the position of the value in array, if the value does not exist then -1 is returned.

Example:

const fruits = ['Mango','Apple','Banana','Orange','Grapes'];

// Find in Array

console.log(fruits.indexOf('Banana')); // Result: 2

// when value in not in array

console.log(fruits.indexOf('abcd')); // Result: -1

 

2. Using Array includes()

 

The includes() method determines whether an array contains a specified element. This method returns true if the array contains the element, and false if not.

 

Example:

const fruits1 = ["Banana", "Orange", "Apple", "Mango"];

console.log(fruits1.includes("Mango")); // Result: true

console.log(fruits1.includes("Pears")); // Result: false

 

3. Using Loop

We can also find the value in the array without any javascript function.  

 

const fruits = ['Mango','Apple','Banana','Orange','Grapes'];

  function findValueInArray(value,arr){

    let result = "Doesn't exist";

      for(var i=0; i<arr.length; i++){

        var name = arr[i];

        if(name == value){

          result = 'Exist';

          break;

        }

      }

    return result;

}

 

console.log(findValueInArray('Banana', fruits)); // Result : Exist

 

console.log(findValueInArray('abc', fruits)); // Result : Doesn't exist

 


WHAT'S NEW

Find other similar Articles here: