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
  • Does this answer your question? [How to compare arrays in JavaScript?](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – A. Meshu Aug 23 '20 at 18:53
  • Have you considered using [indexOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) for this? – ray Aug 23 '20 at 18:55
  • First of all isBP variable is not an array. – Aayush Mall Aug 23 '20 at 18:55
  • isBP is undefined and you use 2 different writings for it. – Sascha Aug 23 '20 at 18:57
  • If you could explain your expected result with this example, we could discuss, what to do. – Nikolaus Aug 23 '20 at 18:58

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
  • 170,828
  • 13
  • 121
  • 150
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,289
  • 11
  • 16