4 Methods to Determine If the Contents of Two Arrays Are Equal
2 min readJun 10, 2024
Given two arrays, how to determine if the content of both arrays is equal without using sorting and without considering the position of elements.
Example:
[1, 2, 3] and [1, 3, 2] // true
[1, 2, 3] and [1, 2, 4] // false
1. Count Elements Frequency
function areArraysContentEqual(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
// Create a counter object to record the frequency of each element in the array
const countMap1 = count(arr1)
const countMap2 = count(arr2)
// Count the frequency of elements in the array
function count(arr = []) {
const resMap = new Map();
for (const item of arr) {
resMap.set(item, (resMap.get(item) || 0) + 1);
}
return resMap
}
// Check if the counter objects are equal
for (const [key, count] of countMap1) {
if (countMap2.get(key) !== count) {
return false;
}
}
return true;
}
const array1 = ["apple", "banana", "cherry", "banana", 1, '1', '11', 11];
const array2 = ["banana", "apple", "banana", "cherry", '1', 1, '11', 11];
areArraysContentEqual(array1, array2) // true
2. One Object
function areArraysContentEqual3(arr1= [], arr2 = []) {
if (arr1.length !== arr2.length) {…