How to use JavaScript compare array?

How to use JavaScript compare array?

Hey Kalyani,

From the query you have posted, I believe you are a beginner, and it’s great to see you are making attempts and using communities like this to explore your knowledge.

I would be happy to guide you with your problem statement here.

So comparing arrays in JavaScript can be done in various ways depending on the type of comparison you need.

One way that worked for me is “Comparing Arrays for Equality” : To check if two arrays contain the same elements in the same order, you can use every method along with length check.

function arraysEqual(arr1, arr2) {
  return arr1.length === arr2.length && arr1.every((value, index) => value === arr2[index]);
}

const array1 = [1, 2, 3];
const array2 = [1, 2, 3];
console.log(arraysEqual(array1, array2)); // true

I hope I was able to help you clear your doubts.

Hey Tim,

Comparing Arrays as Sets (Ignoring Order and Duplicates) : If you need to check if two arrays contain the same elements regardless of order and duplicates, you can convert them to sets and compare.

function arraysEqualAsSets(arr1, arr2) { const set1 = new Set(arr1); const set2 = new Set(arr2); if (set1.size !== set2.size) return false; for (let item of set1) { if (!set2.has(item)) return false; } return true; }

const array3 = [1, 2, 3, 3]; const array4 = [3, 2, 1]; console.log(arraysEqualAsSets(array3, array4)); // true

Hey Dipen

To do deep JavaScript compare Array, I tried an advanced approach.

For deep comparison of nested arrays (arrays within arrays), you can use a recursive function.

function deepEqual(arr1, arr2) {
  if (arr1 === arr2) return true;
  if (arr1 == null || arr2 == null) return false;
  if (arr1.length !== arr2.length) return false;

  for (let i = 0; i < arr1.length; i++) {
    if (Array.isArray(arr1[i]) && Array.isArray(arr2[i])) {
      if (!deepEqual(arr1[i], arr2[i])) return false;
    } else if (arr1[i] !== arr2[i]) {
      return false;
    }
  }
  return true;
}

const nestedArray1 = [1, [2, 3], [4, [5, 6]]];
const nestedArray2 = [1, [2, 3], [4, [5, 6]]];
console.log(deepEqual(nestedArray1, nestedArray2)); // true

The above approach will provide you with a recursive deep comparison suitable for nested arrays