Check Two Arrays Have the Same Elements

If you have been learning JavaScript , you might have came across == or === operator. It does not work as usual with arrays. Because arrays in JavaScript are objects. You won’t be able to find out if two arrays have equal elements at corresponding index values using these operators. In JavaScript, the == operator is used for equality comparison, but when comparing arrays, it checks for reference equality, not structural equality. This means that it checks if both arrays reference the same object in memory, not if they have the same elements.

let arr1=[1, 2, 3, 4] ; 
let arr2=[1, 2, 3, 4];

console.log(arr1 ==arr2); // false
console.log(arr1 === arr2); // false

console.log(JSON.stringify(arr1)); // '[1,2,3,4]'
console.log(JSON.stringify(arr2)); // '[1,2,3,4]'

console.log(JSON.stringify(arr1) == JSON.stringify(arr2)); // true

To find out if two arrays have the same elements , we can use a number of methods. You can compare if every element in one array ,is present in other array and lengths of both arrays are equal. Or, you can find out by first converting array to string .

Below are a few ways to compare arrays for equality:

You need to be logged in to view the rest of the content. Please . Not a Member? Join Us

Pin It on Pinterest

Scroll to Top