0
JS array question
why this code results in 'false', despite both arrays being identical? var arr = ["NORTH", "SOUTH"]; var newArr = [arr[0],arr[1]]; console.log(arr==newArr);
4 Answers
+ 11
Because their content is the same, but they are different objects.
+ 9
1. If the order of the arrays doesn't matter, sort your arrays.
2. You shouldn't use toString to check equality because then you don't know if the elements in the array are values of the same type.
Try to iterate over the arrays in a loop and compare each element. Before that, check if the lengths of the arrays are equal.
+ 4
As a demonstration of @Tashi N answer
console.log(arr[0]==newArr[0]);
will result true as you are comparing the content.
+ 1
Thanks to your feedback Seamini and Tashi I figured out a workaround:
console.log(arr.toString()==newArr.toString());
if you have any suggestions on doing it better, please let me know :)