javascriptarraysarray-comparison

Comparing Two Arrays in Javascript to Find Identical Similarities and Other Similarities


I have two arrays in Javascript: code and submittedCode. I am trying to compare the two arrays. Each of the arrays is 4 integers long, and each integer is a random value of 1 to 6. I also have two variables: red and white. When the two are compared, the red variable should be set to the number of similarities in the arrays that are the same number, same index. White should be set to the number of similarities in the array that are the same number, but different indexes. For example, if the code array is [1, 3, 6, 5] and submittedCode is [1, 6, 4, 5], then red would be set to 2, and white would be set to 1. This is the same logic as the game Mastermind if anyone has played that. Below is what I have tried, but it is not working as intended.

for(let i = 0; i < code.length; i++) {
        if(code[i] == submittedCode[i])
        {
            code.splice(i, 1);
            submittedCode.splice(i, 1);
            red++;
            //console.log(i);
        }
    }
    console.log(code);
    var saveLength = code.length;

    code = code.filter(function(val) {
  return submittedCode.indexOf(val) == -1;
    });

    white = saveLength - code.length;

    console.log(red + ", " + white);

Solution

  • let arr=[1,3,1,2]       //two array we operate on
    let arr2=[4,4,1,2]
    
    let red=0
    let white=0
    
    //we need to check the current length of remaining array
    let currentLength=arr.length            
    
    for(let i=0; i<currentLength; i++){
        if(arr[i]===arr2[i]){       
        arr.splice(i,1)             //if same number same index, remove this item from array
        arr2.splice(i,1)
        currentLength-=1            //currentLength-1 because we reduced the array
        i-=1                                    //i-1 because we'd skip the next element
        red+=1                              //update red
      }
    }
    
    //we basically do the same thing but with white
    //but in the second array we look for the first index of the current element and remove that
    for(let i=0; i<arr.length; i++){
    if(arr2.includes(arr[i])){   
        //1: I should've taken away the item from arr2 first
        //2: arr2.splice(arr2.findIndex(f=>f===arr[i],1))  notice I messed up where I put the 1 at the end
        arr2.splice(arr2.findIndex(f=>f===arr[i]),1)
        arr.splice(i,1)  
        i-=1
        white+=1
    }
    }
    

    Now this might not be the most optimal solution, you can do this in one loop, but for visibility I created 2 for loops, in the first we check the 'red' elements, and we take those out in the second loop we check if there are any 'white' elements, and we take those out.