JavaScript | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

JavaScript

Please describe me: var a = [2, 3, 'foo', 8]; var b = [2, 3, 'fii', 8]; console.log(a == b); Why the answer is false?

22nd Sep 2019, 9:35 AM
Sharifi
Sharifi - avatar
6 Answers
+ 5
Javascript arrays are objects and you can't simply use the equality operator ==. If you want to compare the array you can try a.length === b.length && a.every(e => b.includes(e)) or sneaky way JSON.stringify(a) === JSON.stringify(b); // this could work if the order of both array are the same.
22nd Sep 2019, 9:45 AM
Phurinat Puekkham
Phurinat Puekkham - avatar
+ 3
Phurinat Puekkham It is a nice attempt of you. However, if you don't mind, I like to point out the following : In your example of a.every(e => b.includes(e)); Instead of comparing whether the array contains the same elements, you are checking whether all elements in a is included in b. Because you have not checked the other way round, explicitly whether all elements in b are included in a, you can only conclude that a is subset of b with your method.
22nd Sep 2019, 10:41 AM
Gordon
Gordon - avatar
+ 2
You are welcome, Phurinat. Your revised condition works, for flat array with same sequence only. I have coded a unit testing module for you. https://code.sololearn.com/WEEfAQPM04h8/?ref=app In which you should see that your current way does not pass the third and fourth test case. Try add something to your current comparison function, to make it pass all the test cases.
22nd Sep 2019, 1:54 PM
Gordon
Gordon - avatar
+ 2
Phurinat Puekkham 👍👍👍
22nd Sep 2019, 3:34 PM
Gordon
Gordon - avatar
+ 1
Hi Gordon Thank you for correcting me. So it should be a.length === b.length && a.every(e => b.includes(e))
22nd Sep 2019, 10:54 AM
Phurinat Puekkham
Phurinat Puekkham - avatar
+ 1
Gordon, Thanks for coded a unit test. If you don't care about the order of the elements inside and all elements in the array are a primitive type. This condition still works. a.length === b.length && a.every(e => b.includes(e)) But if the order is important, you can use JSON.stringify(a) === JSON.stringify(b) It will pass all the test cases in https://code.sololearn.com/WEEfAQPM04h8/?ref=app
22nd Sep 2019, 3:03 PM
Phurinat Puekkham
Phurinat Puekkham - avatar