Search code examples
arrayscastingcomparison

How can I get the number of differences between two types of array without casting


I have two types of arrays with the same length:

array1: [2,1,2,3,1]
array2: ["2","2","2","2","1"]

I want to compare them and get the number of differences without casting. For example, for the arrays above, I'm expecting to get the output: 2


Solution

  • This function return the number of elements that different between arrays.

      function compareArrays(x,y){
           var diff = 0;
           x.forEach((elem,index)=>{
                 if(y[index]!=elem){
                     diff++;
                 }
          });
          return diff;
       }
    

    I use == in y[index]==elem thus 1=='1' is true.