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)
reduce
can count up the number of matches pretty concisely:If you want to count only same items per index, you can use
.reduce
as follows:reduce()
is the fit for purpose method, but you can also achieve this by usingfilter()
and accessing thelength
of the returned array of identical elements.