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
Compare arrays using Array.prototype.every() in JavaScript
We are required to write a JavaScript function that takes in two arrays of literals. Then our function should return true if all the elements of first array are included in the second array, irrespective of their count, false otherwise.
We have to use Array.prototype.every() method to make these comparisons.
Syntax
array.every(callback(element, index, array), thisArg)
How Array.every() Works
The every()true if all elements pass the test function, false if any element fails. It stops checking as soon as one element fails the test.
Example
The code for this will be:
const arr1 = [0, 2, 2, 2, 1];
const arr2 = [0, 2, 2, 2, 3];
const compareArrays = (arr1, arr2) => {
const areEqual = arr1.every(el => {
return arr2.includes(el);
});
return areEqual;
};
console.log(compareArrays(arr1, arr2));
Output
And the output in the console will be:
false
Why It Returns False
The function returns false because element 1 from arr1 is not present in arr2. The every() method checks each element of arr1 against arr2 using includes().
More Examples
// Example 1: All elements present const fruits1 = ['apple', 'banana']; const fruits2 = ['apple', 'banana', 'cherry']; console.log(compareArrays(fruits1, fruits2)); // true // Example 2: Missing element const nums1 = [1, 2, 3]; const nums2 = [1, 2, 4]; console.log(compareArrays(nums1, nums2)); // false // Example 3: Empty array const empty = []; const numbers = [1, 2, 3]; console.log(compareArrays(empty, numbers)); // true (vacuously true)
true false true
Optimized Version
We can simplify the function by directly returning the every() result:
const compareArraysOptimized = (arr1, arr2) => {
return arr1.every(el => arr2.includes(el));
};
const test1 = [1, 2, 3];
const test2 = [1, 2, 3, 4, 5];
console.log(compareArraysOptimized(test1, test2));
true
Key Points
-
every()returnstrueonly if ALL elements pass the test - It stops execution as soon as one element fails
- For empty arrays,
every()returnstrue(vacuously true) - This method checks inclusion, not equality of arrays
Conclusion
Using Array.prototype.every() with includes() provides an efficient way to check if all elements of one array exist in another. The method stops early when a mismatch is found, making it performant for large arrays.
