compare two arrays in javascript

To compare two arrays in javascript, we can use the JSON.stringify() method to convert the arrays to strings and then compare the strings. Here is an example:

index.tsx
let arr1 = [1, 2, 3];
let arr2 = [1, 2, 3];

if(JSON.stringify(arr1) === JSON.stringify(arr2)) {
  console.log("Arrays are equal");
} else {
  console.log("Arrays are not equal");
}
182 chars
9 lines

In this example, we use JSON.stringify() to convert arr1 and arr2 to strings and then compare them. If the strings are equal, we print "Arrays are equal", and if they are not equal, we print "Arrays are not equal". Note that this method only works if the arrays contain primitive types (such as numbers, strings, or booleans). If the arrays contain objects or other nested arrays, this method may not return the desired result.

related categories

gistlibby LogSnag