Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

How to compare two arrays in JavaScript

Nouman Abbasi

There are several ways to compare two arrays in JavaScript. We will cover two of them:

  • using JSON.stringify()
  • using lodash library

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.

Lodash

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

RELATED TAGS

javascript

CONTRIBUTOR

Nouman Abbasi
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring