Javascript Comparing Two Arrays
Comparing two arrays in javascript.
Comparing Two Arrays
In Javascript, array is a type of Object and Objects cannot be compared based on their values but of their references.
Convert to string and compare array
JSON.stringify()
We can convert the array into string and compare both using a equality operator
let arr1 = [1,3,5,7];let arr2 = [1,3,5,7];const compareTwoArrays = (a, b) => {return JSON.stringify(a) === JSON.stringify(b);}compareTwoArrays(arr1, arr2) // true
But in the above method, if one array contains null
and another undefined
then also it holds the comparison as true
which is incorrect. So there other ways to make sure the comparison is accurate.
For loop
Let’s see how we can write a for loop to compare arrays.
function compareTwoArrays(a, b) {// Write a guard clause to check the length of both arraysif (a.length !== b.length) return false;for (let i = 0; i < a.length; i++) {if (a[i] !== b[i]){return false}}return true;}let arr1 = [1,3,5,7];let arr2 = [1,3,5,7];compareTwoArrays(arr1, arr2) // truelet arr1 = [1,3,5,7, null];let arr2 = [1,3,5,7, undefined];compareTwoArrays(arr1, arr2) // false
Array.every()
Another way of doing this comparison is by using the built-in every()
method of array.
const compareTwoArrays = (a, b) => {// Write a guard clause to check the length of both arraysif (a.length !== b.length) return false;return a.every((elem, index) => elem === b[index])}let arr1 = [1,3,5,7];let arr2 = [1,3,5,7];compareTwoArrays(arr1, arr2) // truelet arr1 = [1,3,5,7, null];let arr2 = [1,3,5,7, undefined];compareTwoArrays(arr1, arr2) // false