To check if two arrays are equal in TypeScript, you can use the every
method for arrays with the same elements and the JSON.stringify
method for arrays with different elements.
In this example,
arr1
and arr2
with the same elements.every
method to check if the arrays are equal and store the result in the variable equal1
.every
method returns true
if all elements pass the provided function condition, otherwise false
.equal1
to the console.const arr1: number[] = [1, 2, 3];
const arr2: number[] = [1, 2, 3];
const equal1 = arr1.every((val, index) => val === arr2[index]);
console.log(`Arrays are equal: ${equal1}`);
Arrays are equal: true
In this example,
arr3
and arr4
with different elements.JSON.stringify
method to compare the stringified arrays and store the result in the variable equal2
.JSON.stringify
method converts a JavaScript object or value to a JSON string.equal2
to the console.const arr3: number[] = [1, 2, 3];
const arr4: number[] = [3, 2, 1];
const equal2 = JSON.stringify(arr3) === JSON.stringify(arr4);
console.log(`Arrays are equal: ${equal2}`);
Arrays are equal: false
In this tutorial, we learned How to check if Two Arrays are Equal in TypeScript language with well detailed examples.