How to Compare Two JavaScrpt Arrays
This tutorial will show you some ways of comparing two arrays.
The JSON.stringify() method¶
let firstArr = [1, 2, [3, 4, 5]]; let secondArr = [1, 2, [3, 4, 5]]; let isEqual = JSON.stringify(firstArr) === JSON.stringify(secondArr); console.log(isEqual);
If the array contains null and undefined, the given solution won’t work.
The toString() Method¶
You can also invoke toString() for camparing an array of numbers and string:
let firstArr = [1, 2, 3, 4, 5]; let secondArr = [1, 2, 3, 4, 5]; let isEqual = firstArr.toString() === secondArr.toString(); console.log(isEqual);
The Array.prototype.every() Method¶
An alternate way of the above solution is Array.prototype.every() to compare each element of the array with the elements of another array:
let firstArr = [1, 2, 3, 4, 5]; let secondArr = [1, 2, 3, 4, 5]; let isEqual = firstArr.length === secondArr.length && firstArr.every((value, index) => value === secondArr[index]); console.log(isEqual);
Arrays are list-like objects, and their elements are properties with names 0, 1, 2 .. etc. They have special properties: length and many functions that manipulate the elements. Neither the length nor the types of the elements are fixed.
The arrays are zero-indexed, meaning that the first element is at index 0, and the index of the last element is equivalent to the value of the length property minus 1.