Comparing Arrays

Arrays are a common data structure used in application development to store a collection of data. There are many scenarios in which we may need to compare arrays. such as :

  • To check if two arrays contain the same elements
  • To find the difference between two arrays
  • To find the intersection of two arrays
  • To check if an array contains a specific element
  • To sort an elements by comparing its elements
  • To search for an element in an array



The best method to use will depend on the specific application requirement and the data types of the arrays being compared. Here are a few of the most common  methods :

Using the equality operator (== or ===) :

This method compares the values of the elements in the two arrays and return true if all the elements are equal, otherwise it return false.


Using the JSON.stringify() method :

This method converts an array to a string, and then compares the two string. This method is useful if the arrays contain objects or other complex data types.


Using a for loop :

This method iterates through the elements of both arrays and compares each element to the corresponding element in the other arrays.


Using the Array.prototype.every() method :

This method takes a function as an argument and iterates through the elements of the array, calling the function for each element. The function returns true if all the elements pass the test otherwise it is false.


So, now you get an idea of how and when we might need to compare arrays. The most fundamental way to compare arrays is to turn them into strings and then do an equality comparison. But this doesn't work if the order of elements is different in both the arrays.

Comparing two arrays to see if they’re identical may seem like a trivial task but it’s not only required quite often, but there isn’t any ready method available in JavaScript that helps us do it.

In this example, we are comparing two arrays where not only the content is the same, but the position of each element within the array is also the same.

    const array1 = [1, 2, 3, "position"];

    const array2 = [1, 2, 3, "position"];

    const compare = (arr1, arr2) => 
JSON.stringify(arr1) === JSON.stringify(arr2);

    console.log(`Array 1 ${compare(array1, array2) ? 'is' : 'is not'} equal to Array 2`);

    // Output :
    // Array 1 is equal to Array 2

Since we cannot just use the equality operator to compare two arrays directly, we’ll build a function named compare which takes two arrays, and uses the equality operator to compare the string equivalents of the arrays which we’ll get using JSON.stringify(). This is the easiest way to compare two arrays.

When we run this code, we see that our arrays are indeed identical. So, in this case, the two arrays have to be 100% identical to get a truthy match or else we get a false.

   // Both arrays have the same contents
    const arrC = [1, 2, 3, 1, 23, 10, { id: 1 }, { id: 2 }, 'Hello'];
    const arrD = [1, 3, 2, 1, 10, 23, { id: 2 }, 'Hello', { id: 1 }];
    //compare arrays
    const hasSameContents = (arrA, arrB) => {
    //map method on both arrays to convert all content to strings.
    const stringA = arrA.map((el) => JSON.stringify(el));
    const stringB = arrB.map((el) => JSON.stringify(el));
    //return an array from this function
    return [
    //equate the length of both the arrays
    arrA.length === arrB.length,
    ...stringA.map((el) => stringB.includes(el)),
    ...stringB.map((el) => stringA.includes(el)),
    ].every((el) => el);
    };
    console.log(
    "Result :",
    hasSameContents(arrC, arrD)
    ? 'Both arrays have the same elements'
    : 'Both arrays do not have the same elements'
    );
  

   // Output:
   // Both arrays have the same elements

We have these two arrays that have the same content but the position of elements in the arrays is different. Technically the arrays contain the same content, which is why we need a way to equate them to see if they actually have the exact same content or not.

The function named hasSameContents which takes two arrays. In the function, the map method on both arrays converts all content to strings. This is because an array might contain nested arrays or objects in which case we need to convert them to strings before we can equate them.

The first spread operator runs a map function that takes every element of the stringified array A and uses the includes the function to check if it is included in the stringified array B. So, we’re checking if every element of Array A exists in Array B or not. The next spread operator checks if every element in array B exists in Array A.

To ensure that every single element in this array is true for our question ‘Do both arrays have same content’ use the every method that exists on the array prototype. The every method runs a condition for every single element in the array and returns a true if every iteration returned a true. So, if our array is all true, then the every method will return a consolidated true or else false.

This way we can compare two arrays to ensure they carry the same content even if the order of content isn’t the same which doesn’t matter when all you’re doing is accessing or mutating the content and the order of content isn’t important.

Comments

Popular posts from this blog

Filter Method

Fundamental Of Arrays