To check if two arrays have the same elements regardless of order in TypeScript, you can sort both arrays and then compare them using a function.
In this example,
arr1
and arr2
with the same elements but in different order.sort()
method.arraysEqual
that checks if the sorted arrays are equal.arraysEqual
to compare the arrays and print the result to the console.const arr1: number[] = [1, 2, 3];
const arr2: number[] = [3, 1, 2];
function arraysEqual(arr1: number[], arr2: number[]): boolean {
if (arr1.length !== arr2.length) return false;
const sortedArr1 = arr1.sort();
const sortedArr2 = arr2.sort();
return sortedArr1.every((val, index) => val === sortedArr2[index]);
}
console.log(arraysEqual(arr1, arr2));
true
In this example,
arr3
and arr4
with different elements.sort()
method.arraysEqual
that checks if the sorted arrays are equal.arraysEqual
to compare the arrays and print the result to the console.const arr3: number[] = [1, 2, 3];
const arr4: number[] = [4, 5, 6];
function arraysEqual(arr1: number[], arr2: number[]): boolean {
if (arr1.length !== arr2.length) return false;
const sortedArr1 = arr1.sort();
const sortedArr2 = arr2.sort();
return sortedArr1.every((val, index) => val === sortedArr2[index]);
}
console.log(arraysEqual(arr3, arr4));
false
In this tutorial, we learned How to check if Two Arrays have Same Elements (Regardless of Order) in TypeScript language with well detailed examples.