Write a function in javascript that check if two arrays are equal.
Input: array1 = [5, 6, 9, 4, 5, 3, 3] , array2 = [5, 6, 9, 4, 5, 3, 3]
Output: true
Input: array1 = [1,5,9] , array2 = [1,5,9,5,9]
Output: false
function method1(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
for (let i = 0; i < arr1.length; i++) {
const faElem = arr1[i];
const saElem = arr2[i];
if (faElem !== saElem) return false;
}
return true;
}
const array11 = [5, 6, 9, 4, 5, 3, 3];
const array21 = [5, 6, 9, 4, 5, 3, 3];
method1(array11,array21); //output: true
const array12 = [1,5,9];
const array22 = [1,5,9,5,9];
method1(array12,array22); //output: false
function method2(arr1, arr2) {
return JSON.stringify(arr1) === JSON.stringify(arr2);
}
const array11 = [5, 6, 9, 4, 5, 3, 3];
const array21 = [5, 6, 9, 4, 5, 3, 3];
method2(array11,array21); //output: true
const array12 = [1,5,9];
const array22 = [1,5,9,5,9];
method2(array12,array22); //output: false
function method3(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
return arr1.every((val, index) => val === arr2[index]);
}
const array11 = [5, 6, 9, 4, 5, 3, 3];
const array21 = [5, 6, 9, 4, 5, 3, 3];
method3(array11,array21); //output: true
const array12 = [1,5,9];
const array22 = [1,5,9,5,9];
method3(array12,array22); //output: false
function method4(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
const countMap1 = new Map();
const countMap2 = new Map();
for (const elem of arr1) countMap1.set(elem, (countMap1.get(elem) || 0) + 1);
for (const elem of arr2) countMap2.set(elem, (countMap2.get(elem) || 0) + 1);
for (const [key, value] of countMap1) {
if (countMap2.get(key) !== value) return false;
}
return true;
}
const array11 = [5, 6, 9, 4, 5, 3, 3];
const array21 = [5, 6, 9, 4, 5, 3, 3];
method4(array11,array21); //output: true
const array12 = [1,5,9];
const array22 = [1,5,9,5,9];
method4(array12,array22); //output: false