There are several ways to compare two arrays in JavaScript. We will cover two of them:
JSON.stringify()
We first convert the arrays to their stringified version using JSON.stringify()
and then compare using ===
:
const arr1 = [1, 2, 3];const arr2 = [1, 2, 3];console.log(JSON.stringify(arr1) === JSON.stringify(arr2)); // true
Comparing with
JSON.stringify()
may not work for more complex cases (e.g., if you’re comparing arrays of objects and the order of the properties does not matter). Use the method below if you want to cater for that case as well.
The JavaScript library lodash offers the _.isEqual(value1, value2)
function. This function performs a deep comparison between two values to check if they are equivalent.
We can easily use this method to compare two arrays:
import _ from "lodash";const arr1 = [1, 2, 3];const arr2 = [1, 2, 3];console.log(_.isEqual(arr1, arr2)); // true
Free Resources