Answer the question
In order to leave comments, you need to log in
How to find the number of duplicate elements in an array?
Given an array [ '-.........', '.....', '-....-', '.....' ] it is necessary to count duplicate elements.
How to implement?
Answer the question
In order to leave comments, you need to log in
const count = arr.reduce((acc, n) => (acc[n] = (acc[n] || 0) + 1, acc), {});
const duplicateCount = Object.values(count).filter(n => n > 1).length;
const arrayOfDuplicateElements = [ '-.........', '.....', '-....-', '.....' ]
const getNumberOfDuplicateItems = arr => {
const set = new Set()
arr.forEach(el => set.add(el))
const initialArrayLength = arr.length
const uniqueArrayLength = [...set].length
return initialArrayLength - uniqueArrayLength
}
console.log(getNumberOfDuplicateItems(arrayOfDuplicateElements))
const arrayOfDuplicateElements = [ '-.........', '.....', '-....-', '.....' ]
const getNumberOfDuplicateItems = arr => arr.length - [...new Set(arr)].length
console.log(getNumberOfDuplicateItems(arrayOfDuplicateElements))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question