Compare 2 or more JS arrays

Compare 2 or more arrays
Difficulty

Sometimes can be useful an efficient way to verify that two arrays of objects or primitives are the same. In these cases, the simple comparison operator is not enough because arrays are two different instances of objects. We have to compare js arrays that are lists and not simple objects.
For example the following comparison will give an erroneously wrong result:

[true, false, true, false] == [true, false, true, false] // false


The solution is to first check the length and consistency of both arrays under consideration and then check the objects in them.
First we consider the version suitable for javascript, through a function.

  /**
   * Compare 2 given arrays.
   * @param a1
   * @param a2
   */
function compareArrays(a1, a2) {
    if (!a1 && !a2 && a1.length !== a2.length) {
      return false;
    }
    return !a1.some((v, i) => (v !== a2[i]));
}


The one below is the typed method (suitable for typescript frameworks: Angular, React, etc.):

  /**
   * Compare 2 given arrays.
   * @param a1
   * @param a2
   */
  public static compareArrays(a1: any[], a2: any[]): boolean {
    if (!a1 && !a2 && a1.length !== a2.length) {
      return false;
    }
    return !a1.some((v, i) => (v !== a2[i]));
  }


The result will be the following, using our function to compare js arrays:

compareArrays([true, false, false], [true, false, false]); // true
compareArrays([true, false, false, false], [true, false, false]); // false
compareArrays(['equal', false, false, false], ['equal', false, false, false]); // true
compareArrays(['different', false, false, false], ['equal', false, false, false]); // false


That’s all.
Try it at home!

0
Be the first one to like this.
Please wait...

Leave a Reply

Thanks for choosing to leave a comment.
Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published.
Please do NOT use keywords in the name field. Let's have a personal and meaningful conversation.