+ 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?
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.
+ 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.
+ 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.
+ 2
Phurinat Puekkham đđđ
+ 1
Hi Gordon Thank you for correcting me.
So it should be
a.length === b.length && a.every(e => b.includes(e))
+ 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