0

im trying to compare between two arrays, whether they have same value at same place, same values at different places or not the same at all. after comparing I want to enter a char to a third array to indicate the result. my code doesnt work for some reason... its not comparing correctly. what am i doing wrong?

var numInput = [1,2,3,4];
var numArr = [2,5,3,6];
var isBp;
var i,j;
  for ( i = 0; i < 4; i++)
   {
     if (numInput[i] == numArr[i])
     {  isBP[i] = "X"; }
     else
     {
       for ( j = 0; j<4; j++)
       {
         if (numInput[i] == numArr[j])
          {isBP[i] = "O";}
         else
          { isBP[i] = "-"; }
       }

     }

     }

the result should be:

isBP = [O,-,X,-]
Netta
  • 11
  • 2

2 Answers2

0

This is a fairly simple array map operation. If I understand correctly you want an X when they match and an O when they don't and that doesn't exist at all and - when it exists but at different location

var numInput = [1,2,3,4];
var numArr = [2,5,6,4];

var isBP = numInput.map((n,i) => ((n === numArr[i] ? 'X' :  numArr.includes(n) ? '-': 'O')))

console.log(isBP)
charlietfl
  • 169,044
  • 13
  • 113
  • 146
0

It looks like you'd like to output:

  • X if the numbers at the same indexes are equal
    • if they are not equal at the same indexes, but the number is found elsewhere
  • O if the number from the first array doesn't exist in the second at all

if so:

var a1 = [1, 2, 3];
var a2 = [1, 3, 4];

var result = a1.map((n, i) => {
  var match = a2.indexOf(n);
  if (match === i) {
    return "X"
  } else if (match > -1) {
    return "O";
  } else {
    return "-";
  }
});

console.log(result); // prints [ 'X', '-', 'O' ]
daf
  • 1,239
  • 11
  • 16