How comparing two arrays if are equall | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 9

How comparing two arrays if are equall

example: num=[9,4,6] numbers=[6,7,0] if ( num==numbers){alert ("hi")}

5th Mar 2017, 5:55 AM
Didi Georgel Danaila
Didi Georgel Danaila - avatar
8 Answers
+ 10
Comparing anything in JS is quite tricky, always be clear about the conditions you consider true. Should it be == or ===? When comparing arrays two questions pop up: 1. does order matter, i.e. is [1,2] equal to [2,1], then you should sort both first. 2. Do you want shallow or deep compare, I.e. does [{value:1}, 2] equal to [{value:1}, 2]. Just pointing it out. Had a few debugging nightmares due to bad equal conditions. 😁😁😁
5th Mar 2017, 9:43 AM
Nikolay Nachev
Nikolay Nachev - avatar
+ 7
I need this for the function win() in my code OrderTheNumbers. Thanks guys I'll see if it works....I am a little confused
5th Mar 2017, 8:21 AM
Didi Georgel Danaila
Didi Georgel Danaila - avatar
+ 7
the program works anyway but the function win () looks like a 7year child's code
5th Mar 2017, 8:31 AM
Didi Georgel Danaila
Didi Georgel Danaila - avatar
+ 7
@Nikolay thanks nice code. It works.
9th Mar 2017, 5:42 PM
Didi Georgel Danaila
Didi Georgel Danaila - avatar
+ 5
@STEVEN an example?
5th Mar 2017, 6:17 AM
Didi Georgel Danaila
Didi Georgel Danaila - avatar
+ 4
function comp(a,b) { return (a.length != b.length) ? false : a.reduce( function(r,v,i,a) { return (r) ? (v==b[i]) : false; }, true ); } // if a content == b content return true, else false...
5th Mar 2017, 8:15 AM
visph
visph - avatar
+ 4
@Didi, here is how I would do it. That way you can easily extend to 16, 25, .... numbers :D function win(){ var numbers = document.getElementsByClassName('numbers'); var win = true; for (var i in numbers) { if ( numbers[i].innerHTML != numbers[i].id ) { if ( numbers[i].id != numbers.length ) { win = false; break; } } } if (win) { alert(" YOU WIN\n You made "+step+" moves") ; }
5th Mar 2017, 6:06 PM
Nikolay Nachev
Nikolay Nachev - avatar
+ 1
i don't know there is any method or not..but you can use for loop.... for(i=0;i<3;i++)if(num[i]!=numbers)count++;if(count==0)print hi
5th Mar 2017, 6:28 AM
Somnath Ghosh
Somnath Ghosh - avatar