Find the number of duplicates in two or more arrays

I’m trying to compare and find how many duplicates are there in two arrays.

const array1 = [a, b, c, d, e]
const array2 = [b, f, c, z, y]

let identical = 0

for (let i = 0; i < array1.length; i++) {
        if (array1[i] === array2[i]) {
          identical++
        }
      }

console.log(identical)
// returns 2

I did this but I want to use a shorter syntax (ES6 syntax)

3 thoughts on “Find the number of duplicates in two or more arrays”

  1. reduce can count up the number of matches pretty concisely:

    const identical = array1.reduce(
      // on each iteration, return the prior accumulator value
      // (matches found so far)
      // plus one, if the current iteration is a match, otherwise plus zero
      (a, num, i) => a + (num === array2[i]),
      0 // initial value
    );
    
    Reply
  2. If you want to count only same items per index, you can use .reduce as follows:

    const array1 = ['a', 'b', 'c', 'd', 'e'];
    const array2 = ['b', 'f', 'c', 'z', 'y'];
    
    const identical = array1.reduce((acc, item, index) => 
      array2[index]===item ? acc+1 : acc
    , 0);
    
    console.log(identical);
    Reply
  3. reduce() is the fit for purpose method, but you can also achieve this by using filter() and accessing the length of the returned array of identical elements.

    const array1 = ['a', 'b', 'c', 'd', 'e'];
    const array2 = ['b', 'f', 'c', 'z', 'y'];
    
    let identical = array1.filter((e, i) => e === array2[i]).length;
    
    console.log(identical)
    Reply

Leave a Comment