D
D
dargezrogue2019-02-19 16:01:41
JavaScript
dargezrogue, 2019-02-19 16:01:41

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

2 answer(s)
0
0xD34F, 2019-02-19
@dargezrogue

const count = arr.reduce((acc, n) => (acc[n] = (acc[n] || 0) + 1, acc), {});

const duplicateCount = Object.values(count).filter(n => n > 1).length;

C
Codestantin C++dorov, 2019-02-22
@Skolozub09

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))

or
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 question

Ask a Question

731 491 924 answers to any question