In this article we will provide you code to compare two arrays in javascript. Arrays are sequential in nature. In order to compare them, we need to make sure that all the values and their positions must be same in both arrays.
Code Example –
arr1 = [1, 2, "hello", "world", 4.56]
arr2 = [1, 2, "world", "hello", 4.56]
arr3 = [1, 2, "hello", "world", 4.56]
arr4 = arr1
arr5 = [...arr1]
console.log("arr1 = arr2 : ", JSON.stringify(arr1) == JSON.stringify(arr2))
console.log("arr1 = arr3 : ", JSON.stringify(arr1) == JSON.stringify(arr3))
console.log("arr1 = arr4 : ", JSON.stringify(arr1) == JSON.stringify(arr4))
console.log("arr1 = arr5 : ", JSON.stringify(arr1) == JSON.stringify(arr5))
Output –
arr1 = arr2 : false
arr1 = arr3 : true
arr1 = arr4 : true
arr1 = arr5 : true
Other Code Examples –
arr1 = [1, 2, "hello", "world", 4.56]
arr2 = [1, 2, "world", "hello", 4.56]
var i = arr1.length;
while (i--) {
if (arr1[i] !== arr2[i]) return false;
}
return true
arr1 = [1, 2, "hello", "world", 4.56]
arr2 = [1, 2, "world", "hello", 4.56]
arr1.every((v,i)=> v === arr2[i]);
arr1 = [1, 2, "hello", "world", 4.56]
arr2 = [1, 2, "world", "hello", 4.56]
arr1.reduce((a, b) => a && arr2.includes(b), true);
arr1 = [1, 2, "hello", "world", 4.56]
arr2 = [1, 2, "world", "hello", 4.56]
arr1.join('') === arr2.join('');
arr1 = [1, 2, "hello", "world", 4.56]
arr2 = [1, 2, "world", "hello", 4.56]
arr1.toString() === arr2.toString();
arr1 = [1, 2, "hello", "world", 4.56]
arr2 = [1, 2, "world", "hello", 4.56]
arr1 == arr2.toString();