+ 5

Comparing two arrays

Why is an array "a" not equal to an array "b"? https://code.sololearn.com/W5pyBFzbx8AY/?ref=app

20th Mar 2019, 12:52 PM
Solo
Solo - avatar
8 Respostas
+ 9
In JavaScript, both == and === will not do element-wise checking for arrays. They check if the arrays refer to the same object. Even if the content of two arrays are the same, == will return false since they are different objects. In terms of "same object", try doing let a = new Array("a", "b") let b = a alert(a == b) https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript
20th Mar 2019, 1:11 PM
Hatsy Rei
Hatsy Rei - avatar
+ 6
Vasiliy At least according to some of the members in SO, it is better to cycle through instead of doing the stringify workaround to do it in one line, due to certain test cases which would fail silently, resulting in nasty bugs.
20th Mar 2019, 1:28 PM
Hatsy Rei
Hatsy Rei - avatar
+ 6
Blazy You are using JSON.stringify, which would also "work" for new Array(). We were just discussing why JSON.stringify is not a good workaround.
22nd Mar 2019, 11:45 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Hatsy Rei thanks for the reply! So in order to compare two arrays, it is necessary to use the comparison cycle for each value of the array index?
20th Mar 2019, 1:24 PM
Solo
Solo - avatar
22nd Mar 2019, 11:41 AM
Blazy
Blazy - avatar
+ 1
Blazy Nice try, but as answered Hatsy Rei we already discussed it ☺ Follow his link, very useful information on this topic.
22nd Mar 2019, 12:41 PM
Solo
Solo - avatar
0
This is one of the fundamental flaws with js. A variable declared as new Array() is an object and objects cannot be compared, whilst if you declared the array as var a = [ ]; it would have worked to compare them
22nd Mar 2019, 9:40 AM
Blazy
Blazy - avatar
0
Blazy Can you give an example of a code?
22nd Mar 2019, 11:35 AM
Solo
Solo - avatar