Example 1: comparing 2 array
const arr1 = [1, 2, 3];
const arr2 = [1, 3, 3];
if (arr1.length !== arr2.length) return console.log("false");
let j = 0
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] === arr2[j]) {
console.log("yes match", arr1[i], arr2[j]);
}
else{
console.log("no match", arr1[i], arr2[j]);
}
j++;
}
Example 2: javascript compare arrays
Array.prototype.equals = function(arr2) {
return (
this.length === arr2.length &&
this.every((value, index) => value === arr2[index])
);
};
[1, 2, 3].equals([1, 2, 3]);
[1, 2, 3].equals([3, 6, 4, 2]);
Example 3: best way compare arrays javascript
const array1 = ['potato', 'banana', 'soup']
const array2 = ['potato', 'orange', 'soup']
array1 === array2;
JSON.stringify(array1) === JSON.stringify(array2);
const deepArray1 = [{test: 'dummy'}, [['woo', 'ya'], 'weird']]
const deepArray2 = [{test: 'dummy'}, [['woo', 'ya'], 'weird']]
deepArray1 === deepArray2;
JSON.stringify(deepArray1) === JSON.stringify(deepArray2);
Example 4: javascript Compare two arrays regardless of order
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
isEqual([1, 2, 3], [1, 2, 3]);
isEqual([1, 2, 3], [1, '2', 3]);
Example 5: how to compare two arrays javascript
function arraysAreIdentical(arr1, arr2){
if (arr1.length !== arr2.length) return false;
for (var i = 0, len = arr1.length; i < len; i++){
if (arr1[i] !== arr2[i]){
return false;
}
}
return true;
}
Example 6: compare arrays javascript
const array1 = [1,2,3,4]
const array2 = [1,2,3,4]
array1.join() === array2.join()
const array3 = [1,2,3,[1,2,3]]
const array4 = [1,2,3,[1,2,3]]
JSON.stringify(array3) === JSON.stringify(array4)