Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript- Arrays are Equal or Not
Next article icon

JavaScript- Arrays are Equal or Not

Last Updated : 09 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

These are the following approaches to compare two arrays in JavaScript:

1. Using the JSON.stringify() Method

JavaScript provides a function JSON.stringify() method in order to convert an object whether or array into a JSON string. By converting it into JSON strings, we can directly check if the strings are equal or not.

JavaScript
let a1 = [1, 2, 3, 5]; let a2 = [1, 2, 3, 5];  if (JSON.stringify(a1) == JSON.stringify(a2))     console.log("True"); else     console.log("False"); 

Output
True False 

2. Using JavaScript for Loop

In this method, we will compare each element of the array one by one using for loop. we manually check each and every item and return true if they are equal otherwise return false.

JavaScript
let a = [1, 2, 3, 5]; let b = [1, 2, 3, 5];  // If length is not equal if (a.length != b.length)     console.log(false); else {      // Comparing each element of array     for (let i = 0; i < a.length; i++)         if (a[i] != b[i])             return console.log(false);     ;     return console.log(true); } 

Output
True 

3. String Comparison

While JavaScript does not have an inbuilt method to directly compare two arrays, it does have inbuilt methods to compare two strings. Strings can also be compared using the equality operator. Therefore, we can convert the arrays to strings, using the Array join() method, and then check if the strings are equal.

JavaScript
let a = [1, 2, 3, 5]; let b = [1, 2, 3, 5]; let res = a.join() == b.join(); console.log(res); 

Output
true 

4. Using Array every() Method

The Javascript Array.every() method considers all the elements of an array and then further checks whether all the elements of the array satisfy the given condition (passed by in user) or not that is provided by a method passed to it as the argument.

JavaScript
const compareFunc = (a, b) =>     a.length === b.length &&     a.every((element, index) => element === b[index]);  let a = [1, 2, 3, 5]; let b = [1, 2, 3, 5]; console.log(compareFunc(a, b));  

Output
true 

5. Using Lodash _.isEqual() Method

In this approach, we are using the Lodash _.isEqual() method that return boolean value of the result whether that given arrays are equal or not.

JavaScript
// Defining Lodash variable  const _ = require('lodash');  let a1 = [1, 2, 3, 4]  let a2 = [1, 2, 3, 4]  // Checking for Equal Value  console.log("The Values are Equal : "     + _.isEqual(a1, a2)); 

Output:

The Values are Equal : true

6. Using Set

The Set object in JavaScript allows you to store unique values of any type, including arrays. By converting arrays to sets, you can easily compare them, as sets automatically remove duplicate values.

JavaScript
function compareArrays(a1, a2) {     const s1 = new Set(a1);     const s2 = new Set(a2);      if (s1.size !== s2.size) {         return false;     }      for (const item of s1) {         if (!s2.has(item)) {             return false;         }     }      return true; }  const a1 = [1, 2, 3, 4]; const a2 = [4, 3, 2, 7];  console.log(compareArrays(a1, a2));  

Output
true 

7. Using reduce and some Methods

This method involves reducing the arrays into an object that keeps track of the elements and their counts, then comparing these objects.

JavaScript
function arraysEqual(a1, a2) {     if (a1.length !== a2.length) return false;      let countElements = (arr) =>         arr.reduce((acc, val) => {             acc[val] = (acc[val] || 0) + 1;             return acc;         }, {});      let c1 = countElements(a1);     let c2 = countElements(a2);      return !Object.keys(c1).some(key => c1[key] !== c2[key]); }  let a1 = [1, 2, 3, 4]; let a2 = [4, 3, 2, 1]; let a3 = [1, 2, 3, 5];  console.log(arraysEqual(a1, a2)); console.log(arraysEqual(a1, a3));  

Output
true false 

8. Using Array.prototype.sort() Method

This approach leverages the fact that two arrays are equal if they contain the same elements in the same order. By sorting both arrays and then comparing them element by element, we can determine if they are equal. This method is particularly useful for comparing arrays where the order of elements does not matter.

JavaScript
function arraysEqual(a1, a2) {     if (a1.length !== a2.length) return false;      let s1 = a1.slice().sort();     let s2 = a2.slice().sort();      for (let i = 0; i < s1.length; i++) {         if (s1[i] !== s2[i]) return false;     }     return true; } let a1 = [3, 1, 2]; let a2 = [2, 3, 1];  console.log(arraysEqual(a1, a2));  

Output
true 

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.


Next Article
JavaScript- Arrays are Equal or Not

B

bestharadhakrishna
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-array
  • JavaScript-DSA
  • JavaScript-Questions

Similar Reads

    Java Array mismatch() Method with Examples
    The mismatch() method in Java is a utility from the java.util.Arrays class. It is used to compare two arrays element by element and determines the index of the first mismatch. It is quite useful to check whether two arrays contain the same corresponding elements or not. Note: If both arrays have cor
    3 min read
    Java Arrays compare() Method with Examples
    The Arrays compare() method in Java is a part of the java.util package to compare arrays lexicographically (dictionary order). This method is useful for ordering arrays and different overloads for different types including boolean, byte, char, double, float, int, long, short, and Object arrays. Exam
    3 min read
    CopyOnWriteArrayList equals() method in Java with Examples
    CopyOnWriteArrayList equals() method is used to compare two lists. It compares the lists as, both lists should have the same size, and all corresponding pairs of elements in the two lists are equal. Syntax: boolean equals(Object o) Parameters: This function has a single parameter which is object to
    2 min read
    Assert Two Lists for Equality Ignoring Order in Java
    In Java, comparing two lists for equality typically checks both the content and the order of the elements using the equals() method. There are many cases where the order of the elements does not matter, and we only want to ensure that both lists contain the same elements, regardless of their order.
    6 min read
    Java | ==, equals(), compareTo(), equalsIgnoreCase() and compare()
    There are many ways to compare two Strings in Java: Using == operatorUsing equals() methodUsing compareTo() methodUsing compareToIgnoreCase() methodUsing compare() method Method 1: using == operator Double equals operator is used to compare two or more than two objects, If they are referring to the
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences