2018-09-30 22:01:58 +00:00
---
id: 594d8d0ab97724821379b1e6
2020-11-27 18:02:05 +00:00
title: Averages/Mode
2018-09-30 22:01:58 +00:00
challengeType: 5
2019-08-05 16:17:33 +00:00
forumTopicId: 302226
2021-01-13 02:31:00 +00:00
dashedName: averagesmode
2018-09-30 22:01:58 +00:00
---
2020-11-27 18:02:05 +00:00
# --description--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
Write a program to find the [mode ](<https://en.wikipedia.org/wiki/Mode (statistics )> "wp: Mode (statistics)") value of a collection.
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
# --hints--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
`mode` should be a function.
```js
assert(typeof mode === 'function');
2018-09-30 22:01:58 +00:00
```
2020-11-27 18:02:05 +00:00
`mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])` should equal `[6]`
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
```js
assert.deepEqual(mode(arr1), [6]);
```
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
`mode([1, 2, 4, 4, 1])` should equal `[1, 4]` .
2018-09-30 22:01:58 +00:00
```js
2020-11-27 18:02:05 +00:00
assert.deepEqual(mode(arr2).sort(), [1, 4]);
2018-09-30 22:01:58 +00:00
```
2020-11-27 18:02:05 +00:00
# --seed--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
## --after-user-code--
2018-09-30 22:01:58 +00:00
```js
2018-10-20 18:02:47 +00:00
const arr1 = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
const arr2 = [1, 2, 4, 4, 1];
2018-09-30 22:01:58 +00:00
```
2020-11-27 18:02:05 +00:00
## --seed-contents--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
```js
function mode(arr) {
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
return true;
}
```
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
# --solutions--
2018-09-30 22:01:58 +00:00
```js
function mode(arr) {
const counter = {};
let result = [];
let max = 0;
// for (const i in arr) {
arr.forEach(el => {
if (!(el in counter)) {
counter[el] = 0;
}
counter[el]++;
if (counter[el] === max) {
result.push(el);
}
else if (counter[el] > max) {
max = counter[el];
result = [el];
}
});
return result;
}
```