Skip to content
Related Articles

Related Articles

How to compare two arrays in JavaScript ?

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 09 Jun, 2022

In this article, the task is to compare two arrays, & we need to check the length of both arrays that should be the same, the objects present in them are of the same type and each item in one array is equal to the counterpart in another array. By doing this, we can conclude both arrays are the same or not. JavaScript provides a function JSON.stringify() method in order to convert an object or array into a JSON string. By converting into JSON strings, we can directly check if the strings are equal or not.

Example 1: This example uses the 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




<script>
  var a = [1, 2, 3, 5];
  var b = [1, 2, 3, 5];
   
  // Comparing both arrays using stringify
  if(JSON.stringify(a)==JSON.stringify(b))
   document.write("True");
  else
   document.write("False");
   document.write('<br>');
  var f=[1, 2, 4, 5];
  if(JSON.stringify(a)==JSON.stringify(f))
   document.write("True");
  else
   document.write("False");
</script>

Output:

True
False

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

Javascript




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

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.

 

Example 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.

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
var a = [1, 2, 3, 5];
var b = [1, 2, 3, 5];
console.log(isEqual(a, b));
    
//This code is contributed by phasing17

 

Time Complexity: O(n)

Auxiliary Space: O(1)

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!