Is array equal

easy

By - Aman Pareek

Last Updated - 27/08/2024

Problem Statement

Write a function in javascript that check if two arrays are equal.

Example 1

Input: array1 = [5, 6, 9, 4, 5, 3, 3] , array2 = [5, 6, 9, 4, 5, 3, 3]

Output: true

Example 2

Input: array1 = [1,5,9] , array2 = [1,5,9,5,9]

Output: false

Solution 1: Iterative Comparison

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 

Solution 2: Using JSON.stringify()

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 

Solution 3: Using Array.prototype.every()

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 

Solution 4: Using Map for Counting Elements

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 

Popular Solutions