JavaScript Program to Check if Two Arrays are Equal or Not
Last Updated :
19 Oct, 2023
Given two arrays, arr1 and arr2 of equal length N, the task is to find if the given arrays are equal or not.
Two arrays are said to be equal if:
- Both of them contain the same set of elements,
- Arrangements (or permutations) of elements might/might not be the same.
- If there are repetitions, then counts of repeated elements must also be the same for two arrays to be equal.
Examples:
Input: arr1[] = {1, 2, 5, 4, 0}, arr2[] = {2, 4, 5, 0, 1}
Output: Yes
Input: arr1[] = {1, 2, 5, 4, 0, 2, 1}, arr2[] = {2, 4, 5, 0, 1, 1, 2}
Output: Yes
Input: arr1[] = {1, 7, 1}, arr2[] = {7, 7, 1}
Output: No
Sort two arrays and then compare their elements sequentially. If all elements in both arrays match, return true; otherwise, return false. This process ensures that both arrays have the same elements in the same order, confirming their equality.
Example: Below is the implementation:
Javascript
function equalArr(arr1, arr2) {
const N = arr1.length;
const M = arr2.length;
if (N !== M) return false ;
arr1.sort();
arr2.sort();
for (const [i, ele] of arr1.entries()) {
if (ele !== arr2[i]) return false ;
}
return true ;
}
let arr1 = [3, 5, 2, 5, 2];
let arr2 = [2, 3, 5, 5, 2];
if (equalArr(arr1, arr2)) {
console.log( "Yes" );
} else {
console.log( "No" );
}
|
First check if length of arr1 is not equal to the length of arr2 then return false. Then traverse over first array and store the count of every element in the hash map. Then traverse over second array and decrease the count of its elements in the hash map. Hash map, then return false, else decrease the count of that element. Return true at the end, as both the arrays are equal by now.
Example: Below is the implementation:
Javascript
function areEqual(arr1, arr2) {
let N = arr1.length;
let M = arr2.length;
if (N != M)
return false ;
let map
= new Map();
let count = 0;
for (let i = 0; i < N; i++) {
if (map.get(arr1[i]) == null )
map.set(arr1[i], 1);
else {
count = map.get(arr1[i]);
count++;
map.set(arr1[i], count);
}
}
for (let i = 0; i < N; i++) {
if (!map.has(arr2[i]))
return false ;
if (map.get(arr2[i]) == 0)
return false ;
count = map.get(arr2[i]);
--count;
map.set(arr2[i], count);
}
return true ;
}
let arr1 = [3, 1, 2, 5, 2];
let arr2 = [2, 3, 5, 5, 2];
if (areEqual(arr1, arr2))
console.log( "Yes" );
else
console.log( "No" );
|
Share your thoughts in the comments
Please Login to comment...