In Javascript, to compare two arrays we need to check that the length of both arrays should be same, the objects present in it 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() in order to convert an object or array into JSON string. By converting into JSON string we can directly check if the strings are equal or not.
Example #1:
<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 checking each and every item and return True if they are equal otherwise return False.
<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 { // comapring 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
Recommended Posts:
- How to compare two JavaScript array objects using jQuery/JavaScript ?
- Compare two dates using JavaScript
- Compare the Case Insensitive strings in JavaScript
- Optimum way to compare strings in JavaScript
- How to compare date part only without comparing time in JavaScript?
- Compare Dates in Java
- Java | ==, equals(), compareTo(), equalsIgnoreCase() and compare()
- Node.js | Buffer.compare() Method
- strings.Compare() Function in Golang with Examples
- Compare Println vs Printf in Golang with Examples
- How to Compare Equality of Struct, Slice and Map in Golang?
- How to compare Structs with the Different Values Assigned to Data Fields in Golang?
- How to find if two arrays contain any common item in Javascript?
- Find the common elements of more than two JavaScript arrays ?
- How to print unique elements from two unsorted arrays using JavaScript ?
- New features of JavaScript Arrays with ES2015
- Arrays in JavaScript
- Converting JavaScript Arrays into CSVs and Vice-Versa
- JavaScript | JSON Arrays
- Compute the set difference using JavaScript arrays
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


