Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to test the equality of two arrays - JavaScript
We are required to write a JavaScript function that takes in two arrays of literals and checks the corresponding elements of the array and it should return true if all the corresponding elements of the array are equal otherwise it should return false.
Let's write the code for this function ?
Example
Following is the code ?
const arr1 = [1, 4, 5, 3, 5, 6];
const arr2 = [1, 4, 5, 2, 5, 6];
const areEqual = (first, second) => {
if(first.length !== second.length){
return false;
};
for(let i = 0; i < first.length; i++){
if(first[i] === second[i]){
continue;
}
return false;
};
return true;
};
console.log(areEqual(arr1, arr2));
Output
Following is the output in the console ?
false
Method 1: Using for loop (Optimized)
We can simplify the logic by directly returning false when elements don't match:
const arr1 = [1, 2, 3, 4];
const arr2 = [1, 2, 3, 4];
const areEqual = (first, second) => {
if(first.length !== second.length){
return false;
}
for(let i = 0; i < first.length; i++){
if(first[i] !== second[i]){
return false;
}
}
return true;
};
console.log(areEqual(arr1, arr2));
console.log(areEqual([1, 2, 3], [1, 2, 4]));
true false
Method 2: Using every() Method
The every() method provides a more functional approach:
const areEqual = (first, second) => {
return first.length === second.length &&
first.every((element, index) => element === second[index]);
};
console.log(areEqual([1, 2, 3], [1, 2, 3]));
console.log(areEqual([1, 2, 3], [1, 2]));
console.log(areEqual(['a', 'b'], ['a', 'c']));
true false false
Method 3: Using JSON.stringify() (Simple Arrays Only)
For arrays containing only primitive values, JSON comparison works:
const areEqual = (first, second) => {
return JSON.stringify(first) === JSON.stringify(second);
};
console.log(areEqual([1, 2, 3], [1, 2, 3]));
console.log(areEqual(['x', 'y'], ['x', 'z']));
console.log(areEqual([1, 2], [2, 1])); // Order matters
true false false
Comparison
| Method | Performance | Nested Arrays | Readability |
|---|---|---|---|
| for loop | Fast | No | Good |
| every() | Good | No | Excellent |
| JSON.stringify() | Slower | Yes | Simple |
Key Points
- Always check array lengths first for performance
- Use strict equality (===) to avoid type coercion
- The
every()method is most readable for functional programming - JSON.stringify() works for nested arrays but is slower
Conclusion
The for loop approach offers the best performance for simple array comparison. Use every() for cleaner, more readable code in functional programming style.
