How to Compare Two Arrays in JavaScript

How to Compare Two Arrays in JavaScript

Let’s start with the most straightforward method, which is to use JSON.stringify() and the === operator to check if the stringified versions of the arrays are equal.

Here is an example:

// Define the arrays to compare
const actionMovies = ["Die Hard", "Lethal Weapon", "Mission Impossible"];
const comedyMovies = ["Dumb and Dumber", "The Hangover", "Anchorman"];

// Check if the arrays are equal
if (JSON.stringify(actionMovies) === JSON.stringify(comedyMovies)) {
console.log("The arrays are equal");
} else {
console.log("The arrays are not equal");
}

In the example above, the JSON.stringify() method is used to convert the arrays to strings, and the === operator is used to compare the strings. If the arrays are equal, the if statement will print “The arrays are equal” to the console, otherwise it will print “The arrays are not equal”.

Array.prototype.every()

Alternatively, you can use the Array.prototype.every() method to compare the elements of the two arrays. The every() method returns true if every element in the array satisfies the provided testing function and false otherwise.

Here is an example:

// Define the arrays to compare
const primaryColors = ["red", "yellow", "blue"];
const secondaryColors = ["orange", "green", "purple"];

// Check if the arrays are equal
if (primaryColors.every((element, index) => element === secondaryColors[index])) {
console.log("The arrays are equal");
} else {
console.log("The arrays are not equal");
}

// Output: The arrays are not equal

In the example above, the every() method is called on the primaryColors array, and it is passed a callback function that compares each element of the primaryColors array to the corresponding element of the secondaryColors array.

A slightly better way to do this would be to use every together with length, like so:

// Define the arrays to compare
const array1 = [1, 2, 3, 4, 5];
const array2 = [1, 2, 3, 4];

// Check if the arrays are equal
if (array1.length !== array2.length) {
console.log("The arrays are not equal");
} else if (array1.every((element, index) => element === array2[index])) {
console.log("The arrays are equal");
} else {
console.log("The arrays are not equal");
}

// Output: The arrays are not equal

Using the length property in this context improves the efficiency and accuracy of the comparison. By checking the lengths of the arrays first, the code can quickly determine if the arrays are not equal without comparing each element.

This saves time and resources, especially if the arrays are large. It also avoids potential errors, such as accessing an element in the second array that does not exist, which could cause the .every() method to return an incorrect result.

By using the length property, the code can also handle cases where the arrays are not equal in length, which would not be possible with the .every() method alone.

Array.prototype.filter() & Set

The above examples compare arrays in order, but there might be cases where you want to compare arrays regardless of order. Instead, you only need to verify that identical values are present in each array.

In that case, you can use filter together with the Set:

// Define the arrays to compare
const array1 = [1, 2, 3, 4, 5];
const array2 = [3, 4, 5, 6, 7];

// Create sets from the arrays
const [set1, set2] = [new Set(array1), new Set(array2)];

// Find common elements
const common = [...set1].filter(x => set2.has(x));

// Check if the number of occurrences is the same in both arrays
let equal = true;
common.forEach(value => {
if (array1.filter(x => x === value).length !== array2.filter(x => x === value).length) {
equal = false;
}
});

// Output: true
console.log(equal);
console.log(common);

This example checks if the number of occurrences of the common elements is the same in both arrays. To do this, we use a forEach() loop to iterate over the common elements and compare the counts for each element. If all counts are equal, the code should return the equal variable as true. If any count is not equal, the code sets the equal variable to false.

Finally, for this example, we also log the value of the equal variable and the common array to the console, so you can see the comparison result.

Previous Post
How to Reverse a String in JavaScript

How to Reverse a String in JavaScript

Next Post

13 Useful CSS Gradient Generators

Related Posts