Wednesday, May 8, 2024
HomeLanguagesPhpHow to compare two arrays in JavaScript ?

How to compare two arrays in JavaScript ?

In this article, we will see how to compare two arrays in JavaScript. First, we need to compare the length of both arrays should be the same or not, and then whether objects present in them are of the same type and whether each item of one array is equal to the other array or not.

Methods to compare two arrays in JavaScript:

Method 1: Using the JSON.stringify() Method

JavaScript provides a function JSON.stringify() method in order to convert an object whether or array into a JSON string. By converting it into JSON strings, we can directly check if the strings are equal or not.

Example: This example uses JSON.stringify() method to convert an object or array into a JSON string, then accordingly check for the given condition. If it satisfies the specific condition then it returns true otherwise, it will return false.

Javascript




// Declare two arrays
let arr1 = [1, 2, 3, 5];
let arr2 = [1, 2, 3, 5];
 
// Comparing both arrays using stringify method
if (JSON.stringify(arr1) == JSON.stringify(arr2))
    console.log("True");
else
    console.log("False");
    
// Declare another array
let arr3 = [1, 2, 4, 5];
 
// Comparing both arrays using stringify method
if (JSON.stringify(arr1) == JSON.stringify(arr3))
    console.log("True");
else
    console.log("False");


Output

True
False

Method 2: Using for Loop element

In this method, we will compare each element of the array one by one using for loop.

Example: In this example, we manually check each and every item and return true if they are equal otherwise return false.

Javascript




function isEqual() {
    let a = [1, 2, 3, 5];
    let b = [1, 2, 3, 5];
 
    // If length is not equal
    if (a.length != b.length)
        return "False";
    else {
 
        // Comparing each element of array
        for (let i = 0; i < a.length; i++)
            if (a[i] != b[i])
                return "False";
        return "True";
    }
}
let v = isEqual();
 
console.log(v);


Output

True

Method 3: String Comparison

While JavaScript does not have an inbuilt method to directly compare two arrays, it does have inbuilt methods to compare two strings. Strings can also be compared using the equality operator. Therefore, we can convert the arrays to strings, using the Array join() method, and then check if the strings are equal.

Example:

Javascript




// JavaScript program to implement the approach
 
// Function that converts the arrays to strings
// and then compares the strings
function isEqual(a, b) {
    return a.join() == b.join();
}
 
// Driver Code
let a = [1, 2, 3, 5];
let b = [1, 2, 3, 5];
 
console.log(isEqual(a, b));


Output

true

Method 4: Using Array every() Method

The Javascript Array.every() method considers all the elements of an array and then further checks whether all the elements of the array satisfy the given condition (passed by in user) or not that is provided by a method passed to it as the argument.

Javascript




const compareFunc = (a, b) =>
    a.length === b.length &&
    a.every((element, index) => element === b[index]);
 
let a = [1, 2, 3, 5];
let b = [1, 2, 3, 5];
console.log(compareFunc(a, b));


Output

true

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments