Signup/Sign In
PUBLISHED ON: MARCH 3, 2023

JavaScript Program to Compare Elements of Two Arrays

Arrays are a basic data structure in JavaScript that allows us to store and modify data collections. Occasionally we need to compare two arrays to check if they contain the same elements or if they differ. This article will show you how to create a JavaScript application that compares the elements of two arrays.

We will look at various array comparison methods and present examples to assist you learn how to use this code in your projects.

We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.

Program to Compare Elements of Two Arrays Using JSON.stringify()

The JSON.stringify() method in Javascript is used to create a JSON string out of it. Both the arrays are compared using the == operator.

?// JavaScript Program to compare two arrays

function compareArrays(arr1, arr2) {

    // compare arrays
    const res = JSON.stringify(arr1) == JSON.stringify(arr2)
    
    if(res) 
       console.log('Both the arrays have the same elements.');
    
    else 
        console.log('The arrays have different elements.'); 

}

const arr1 = [21, 3, 15, 8 , 11 , 7 , 18];
const arr2 = [21, 3, 15, 11 , 8 , 18, 7];

compareArrays(arr1, arr2);


Both the arrays have the same elements.

Program to Compare Elements of Two Arrays using for Loop

// JavaScript Program to extract value as an array from an array of objects

function compareArrays(arr1, arr2) {

    // checking the length
    if(arr1.length != arr2.length) 
        return false;
    }
    else { 
        let result = false;
        
        // comparing each element of array 
        for(let i=0; i<arr1.length; i++) {

            if(arr1[i] != arr2[i]) 
                return false;
            
            else 
                result = true;
            

        }
        return result;     
  }
}

const arr1 = [1, 3, 15, 8 , 11 , 18];
const arr2 = [11, 3, 5, 18, 1, 8];

const result = compareArrays(arr1, arr2);

// if result is true
if(result) 
    console.log('Both the arrays have the same elements.');
else 
    console.log('Both the arrays have different elements.');


Both the arrays have the same elements.

Conclusion

We saw in the article how to prepare a JavaScript program to compare the elements of two arrays in this article. The main thing is to grasp the underlying principles so that you can make the best choice for your individual use case, whether you utilize a loop or comparison operators.



About the author:
Proficient in the creation of websites. Expertise in Java script and C#. Discussing the latest developments in these areas and providing tutorials on how to use them.