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);

20th Apr 2017, 7:41 PM
Simon Nadolski
Simon Nadolski - avatar
4 odpowiedzi
+ 11
Because their content is the same, but they are different objects.
20th Apr 2017, 7:48 PM
Tashi N
Tashi N - avatar
+ 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.
20th Apr 2017, 8:15 PM
Tashi N
Tashi N - avatar
+ 4
As a demonstration of @Tashi N answer console.log(arr[0]==newArr[0]); will result true as you are comparing the content.
20th Apr 2017, 7:52 PM
seamiki
seamiki - avatar
+ 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 :)
20th Apr 2017, 8:02 PM
Simon Nadolski
Simon Nadolski - avatar