-5

For example, I have an array like this;

var arr = [0,0,1,2,2,3,4,5,5,5,6,7,7,7,7,8,9,10,10,10]

My goal is to throw unique elements in the array and get the most repeated numbers.

var arr = [7,7,7,7]

How can this be achieved in JavaScript?

Francesco
  • 9,947
  • 7
  • 67
  • 110
Hüseyin
  • 11
  • 4
  • 10
    Any efforts so far ? please post the code you have tried so far ? – Code Maniac Aug 28 '19 at 10:50
  • 1
    And what if there's a tie? What should be the result for `[1, 1, 2, 2]`? What about `[]`? And are the elements always sorted or is `[1, 2, 1]` a possibility? – Amadan Aug 28 '19 at 10:52
  • 4
    Welcome to Stack Overflow! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder Aug 28 '19 at 10:52
  • 2
    Possible duplicate of [Extracting the most duplicate value from an array in JavaScript (with jQuery)](https://stackoverflow.com/questions/2440295/extracting-the-most-duplicate-value-from-an-array-in-javascript-with-jquery) – Carsten Løvbo Andersen Aug 28 '19 at 10:55
  • `var arr = [0,0,1,2,2,3,4,5,5,5,6,7,7,7,7,8,9,10,10,10]; const f = arr.reduce( (a, b, i, arr) => (arr.filter(v => v === a).length >= arr.filter(v => v === b).length?a:b), null); let result = arr.filter((value) => value === f); console.log(result);` – Hossein Zare Aug 28 '19 at 10:58
  • Thanks for response .@Amadan it sorted array. – Hüseyin Aug 28 '19 at 11:52

1 Answers1

1

var arr = [0, 0, 1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7, 7, 7, 8, 9, 10, 10, 10]

var uniq = arr.reduce((all, next) => {
  var exist = all.find(v => v.key === next)
  if (exist) {
    exist.count += 1
    exist.val.push(next)
  } else {
    all.push({
      key: next,
      count: 1,
      val: [next]
    })
  }
  return all
}, [])

var max = uniq[0]
uniq.forEach(item => {
  if (item.count > max.count) {
    max = item
  }
})

console.log(max.val)
Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69