How to useSorting() in Javascript
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:
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");
}
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
Contact Us