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:

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");
}

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

Similar Reads

Approach 1: Using Sorting()

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....

Approach 2: Using Hashing()

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....

Approach 3: Using Frequency Map with Reduce

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....