Categories: JavaScript

How to check value exists in an array using Javascript?

In this tutorial you will going to lean some method to check value exists in an array using JavaScript.

Method 1 : Use the indexOf()

You can use the indexOf() method to check whether a specific value exists in an array or not. The indexOf() method returns the index of the element within the array if found, and -1 if not found.

Let’s look at the following example for better understand:

<script>    
    var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

    // Check if a value exists in the fruits array
    if(fruits.indexOf("Mango") !== -1){
        alert("Value exists!")
    } else{
        alert("Value does not exists!")
    }
</script>

Method 2 : Use the include()

ES6 introduced include() method to value exists in an array very easy. However, this method only returns true or false instead of the index number, as you can see here:

<script>    
    var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
    alert(fruits.includes("Banana")); // Outputs: true
    alert(fruits.includes("Coconut")); // Outputs: false
    alert(fruits.includes("Orange")); // Outputs: true
    alert(fruits.includes("Cherry")); // Outputs: false
</script>

Method 3 : Old JavaScript Loop 🙁

You can also use the for loop to check value exists in an array. This method little old but you can also do this.

<script type = 'text/javascript' >

//code to check if a value exists in an array using javascript for loop
var fruits_arr = ['Apple', 'Mango', 'Grapes', 'Orange', 'Fig', 'Cherry'];

function checkValue(value, arr) {
    var status = 'Not exist';

    for (var i = 0; i < arr.length; i++) {
        var name = arr[i];
        if (name == value) {
            status = 'Exist';
            break;
        }
    }

    return status;
}

console.log('status : ' + checkValue('Mango', fruits_arr));
console.log('status : ' + checkValue('Peach', fruits_arr)); 

Check if an array contains an object

Suppose sometime you want to find array contains an object that time you find difficulty how you can do this. This time you can use following method using include()

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

In the above example, the list.includes(john) has returns true because the list array has or contains the john object reference.

Suppose you want o find array within a object using value not with the full object that time you have to write one more function for check equal first and second value. Following is the full example

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

Interview Questions for Laravel Developer

Reverse Number in PHP

What is useQuery in react

PHP Interview Questions and Answers

Difference Between Post and Get Method

Difference Between MyISAM and InnoDB

Conclusion

Hope you understand the different method to find value in array. You have to do just practice and check all the above suggested example. Note for object you have to use isEqual extra function which check both the value in the object.

Developer Diary

Share
Published by
Developer Diary

Recent Posts

Git Tag Cheat Sheet

Introduction Git tags are an essential feature of version control systems, offering a simple way…

3 months ago

Understanding Web Storage: Cookies, Local Storage

Introduction The methods that browsers employ to store data on a user's device are referred…

3 months ago

Setting up OpenVPN Access Server in Amazon VPC – AWS

Introduction A well-known open-source VPN technology, OpenVPN provides strong protection for both people and businesses.…

3 months ago

Enhance Error Tracking & Monitoring: Integrate Sentry with Node.js & Express.js

Introduction Integrating Sentry into a Node.js, Express.js, and MongoDB backend project significantly enhances error tracking…

4 months ago

Comparing Callbacks, Promises, and Async/Await in JavaScript

Introduction In the world of JavaScript development, efficiently managing asynchronous operations is essential. Asynchronous programming…

5 months ago

How To Secure Nginx with Let’s Encrypt on Ubuntu EC2 Instance

Introduction Let's Encrypt is a Certificate Authority (CA) that makes it simple to obtain and…

7 months ago