Sign Up

Have an account? Sign In Now

Sign In

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask question.

Forgot Password?

Need An Account, Sign Up Here

You must login to add post.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Passionable Logo Passionable Logo
Sign InSign Up

Passionable

Passionable Navigation

  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • New Questions
  • Trending Questions
  • Must read Questions
  • Hot Questions
Home/ Questions/Q 8901
In Process
Alek Richter
  • 0
Alek RichterEnlightened
Asked: January 11, 20222022-01-11T10:11:15+00:00 2022-01-11T10:11:15+00:00

How to compare arrays in JavaScript?

  • 0

I’d like to compare two arrays… ideally, efficiently. Nothing fancy, just true if they are identical, and false if not. Not surprisingly, the comparison operator doesn’t seem to work.

var a1 = [1,2,3];
var a2 = [1,2,3];
console.log(a1==a2);    // Returns false
console.log(JSON.stringify(a1)==JSON.stringify(a2));    // Returns true

JSON encoding each array does, but is there a faster or “better” way to simply compare arrays without having to iterate through each value?

  • 1 1 Answer
  • 2 Views
  • 0 Followers
  • 0
    • Report
  • Share
    Share
    • Share on Facebook
    • Share on Twitter
    • Share on LinkedIn
    • Share on WhatsApp

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Alek Richter Enlightened
    2022-01-11T10:11:42+00:00Added an answer on January 11, 2022 at 10:11 am

    To compare arrays, loop through them and compare every value:
    Comparing arrays:

    // Warn if overriding existing method
    if(Array.prototype.equals)
    console.warn(“Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there’s a framework conflict or you’ve got double inclusions in your code.”);
    // attach the .equals method to Array’s prototype to call it on any array
    Array.prototype.equals = function (array) {
    // if the other array is a falsy value, return
    if (!array)
    return false;

    // compare lengths – can save a lot of time
    if (this.length != array.length)
    return false;

    for (var i = 0, l=this.length; i not equal
    return false;
    }
    }
    //Now a deeper check using other objects property names
    for(propName in object2) {
    //We must check instances anyway, there may be a property that only exists in object2
    //I wonder, if remembering the checked values from the first loop would be faster or not
    if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
    return false;
    }
    else if (typeof this[propName] != typeof object2[propName]) {
    return false;
    }
    //If the property is inherited, do not check any more (it must be equa if both objects inherit it)
    if(!this.hasOwnProperty(propName))
    continue;

    //Now the detail check and recursion

    //This returns the script back to the array comparing
    /**REQUIRES Array.equals**/
    if (this[propName] instanceof Array && object2[propName] instanceof Array) {
    // recurse into the nested arrays
    if (!this[propName].equals(object2[propName]))
    return false;
    }
    else if (this[propName] instanceof Object && object2[propName] instanceof Object) {
    // recurse into another objects
    //console.log(“Recursing to compare “, this[propName],”with”,object2[propName], ” both named “”+propName+”””);
    if (!this[propName].equals(object2[propName]))
    return false;
    }
    //Normal value comparison for strings and numbers
    else if(this[propName] != object2[propName]) {
    return false;
    }
    }
    //If everything passed, let’s say YES
    return true;
    }

    However, remember that this one is to serve in comparing JSON like data, not class instances and other stuff. If you want to compare more complicated objects, look at this answer and it’s super long function.
    To make this work with Array.equals you must edit the original function a little bit:

    …
    // Check if we have nested arrays
    if (this[i] instanceof Array && array[i] instanceof Array) {
    // recurse into the nested arrays
    if (!this[i].equals(array[i]))
    return false;
    }
    /**REQUIRES OBJECT COMPARE**/
    else if (this[i] instanceof Object && array[i] instanceof Object) {
    // recurse into another objects
    //console.log(“Recursing to compare “, this[propName],”with”,object2[propName], ” both named “”+propName+”””);
    if (!this[i].equals(array[i]))
    return false;
    }
    else if (this[i] != array[i]) {
    …

    I made a little test tool for both of the functions.
    Bonus: Nested arrays with indexOf and contains

    Samy Bencherif has prepared useful functions for the case you’re searching for a specific object in nested arrays, which are available here: https://jsfiddle.net/SamyBencherif/8352y6yw/

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
Leave an answer

Leave an answer
Cancel reply

Browse

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 4k
  • Best Answers 0
  • Users 3
  • Popular
  • Answers
  • Alek Richter

    Truth value of a Series is ambiguous. Use a.empty, a.bool(), ...

    • 2 Answers
  • Alek Richter

    What is a NullPointerException, and how do I fix it?

    • 2 Answers
  • Alek Richter

    Make MS Word document look like it has been typeset ...

    • 2 Answers
  • Alek Richter
    Alek Richter added an answer Pandas DataFrame columns are Pandas Series when you pull them… January 13, 2022 at 2:21 pm
  • Alek Richter
    Alek Richter added an answer The handshake failure could have occurred due to various reasons:… January 13, 2022 at 2:19 pm
  • Alek Richter
    Alek Richter added an answer Mac OS X doesn't have apt-get. There is a package… January 13, 2022 at 2:18 pm

Top Members

Alek Richter

Alek Richter

  • 4k Questions
  • 1k Points
Enlightened
coinbaseprosupportnumber[Xsdwerfgtyujhnbgfderewqasdxz]

coinbaseprosupportnumber[Xsdwerfgtyujhnbgfderewqasdxz]

  • 2 Questions
  • 2 Points

Trending Tags

questin question

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • New Questions
  • Trending Questions
  • Must read Questions
  • Hot Questions

© 2021 Passionable. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.