Introduction
In this lab, we will explore how to check if two arrays have the same contents in JavaScript. We will create a function that takes in two arrays and returns true if they contain the same elements, regardless of order, and false otherwise. We will use a combination of Set, for...of loop, and Array.prototype.filter() to achieve this functionality.
Checking for Same Contents in Arrays
To check if two arrays contain the same elements regardless of order, follow these steps:
- Open the Terminal/SSH and type
node. - Use a
for...ofloop over aSetcreated from the values of both arrays. - Use
Array.prototype.filter()to compare the amount of occurrences of each distinct value in both arrays. - Return
falseif the counts do not match for any element,trueotherwise.
Here's the code for the same:
const haveSameContents = (a, b) => {
for (const v of new Set([...a, ...b]))
if (a.filter((e) => e === v).length !== b.filter((e) => e === v).length)
return false;
return true;
};
To test the function, use the following code:
haveSameContents([1, 2, 4], [2, 4, 1]); // true
Summary
Congratulations! You have completed the Check if Arrays Have Same Contents lab. You can practice more labs in LabEx to improve your skills.