0

Let's say I have two arrays. The first one is [12, 32, 65, 32] and the second is [0, 4, 12, 12]

How would I create a function that looks at each number of each array, and sees how many numbers of the arrays are equal to each other. This is the gists of what I'm attempting to do:

let array1 = [12, 32, 65, 32];
let array2 = [0, 4, 12, 12];
var counter = 0;

for (var i=0; i<= array1.length; i++) {
  //this is where I lose it
  for (var j=0; i<= array2.length; j++) {
    if (array1[i] == array2[j]) {
      counter++;
      console.log(counter);
    }
  }
}

obviously, the function above hopefully allows you to get 1 as your log, because the first array only has one 12. I can't figure out how to make it only give an output of 1 with one 12 for array1 and two in array2. If it were to have two 12s in array1 than of course, the output should be 2.

chriscrutt
  • 500
  • 3
  • 5
  • 17

1 Answers1

1

You can use a Set to get make the arrays contain only unique numbers and the efficiently test if one number is in another array. Then you can just iterate of one set and increment the count if the number is in the other:

let array1 = [12, 32, 65, 32];
let array2 = [0, 4, 12, 12];

function countSame(a1, a2){
  /* Make sets */
  let [s1, s2] = [new Set(a1), new Set(a2)]
  let count = 0

  /* iterate and count */
  for (n of s1){
    if (s2.has(n)) count++
  }
  return count
}


console.log(countSame(array1, array2))

// with more dupes - return 2 because 1 and 3 are common
console.log(countSame([1, 1, 2, 3, 4], [1, 3, 3, 6, 7]))
Mark
  • 90,562
  • 7
  • 108
  • 148