How to useFrequency Map with Reduce in Javascript
This approach also involves creating frequency maps for both arrays and then comparing these maps. Instead of iterating manually to build the frequency maps, we can use the reduce method to streamline the process.
Example:
function areArraysEqual(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
const frequencyMap1 = arr1.reduce((acc, val) => {
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});
const frequencyMap2 = arr2.reduce((acc, val) => {
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});
for (let key in frequencyMap1) {
if (frequencyMap1[key] !== frequencyMap2[key]) {
return false;
}
}
return true;
}
// Driver code
let arr1 = [3, 1, 2, 5, 2];
let arr2 = [2, 3, 5, 1, 2];
if (areArraysEqual(arr1, arr2)) {
console.log("Yes");
} else {
console.log("No");
}
Output
Yes
JavaScript Program to Check if Two Arrays are Equal or Not
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