-2

Say I have 2 arrays:

var array1 = [1, 2, 3];
var array2 = [1, 2, 3, 4];

How do I compare them to single out the element ( in this case the number 4 )?

Something like:

 if ( array1 == array2 ) {
    //then do this
 }else{
    // find out the one that isn't the same in each and show it here
 }
Keith
  • 4,059
  • 2
  • 32
  • 56
  • simple google search for "javascript array comparison -- find differences reveals this: http://stackoverflow.com/questions/3432929/comparing-two-arrays-in-javascript-returning-differences – Snowmonkey Dec 28 '16 at 20:02
  • what if `var array1 = [1, 2, 3,4]; var array2 = [1, 2, 3];` & `var array1 = [1, 2, 3]; var array2 = [1, 2, 4];` – Pranav C Balan Dec 28 '16 at 20:07

1 Answers1

2

You can use Array.prototype.find to do the same

check this snippet

var array1 = [1, 2, 3];
var array2 = [1, 2, 3, 4];
function findNumber(number) { 
    return number=== 4?true:false;
}
var number=array2.find(findNumber);
if(number)
  console.log("found");
else
  console.log("not found");

Hope it helps

Geeky
  • 7,420
  • 2
  • 24
  • 50