2018-09-30 23:01:58 +01:00
---
2019-07-29 07:14:15 -07:00
title: Averages/Mode
2018-09-30 23:01:58 +01:00
id: 594d8d0ab97724821379b1e6
challengeType: 5
2019-08-05 09:17:33 -07:00
forumTopicId: 302226
2018-09-30 23:01:58 +01:00
---
## Description
< section id = 'description' >
2019-03-01 17:10:50 +09:00
Write a program to find the < a href = 'https://en.wikipedia.org/wiki/Mode (statistics)' title = 'wp: Mode (statistics)' target = '_blank' > mode< / a > value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
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 23:01:58 +01:00
< / section >
## Instructions
< section id = 'instructions' >
< / section >
## Tests
< section id = 'tests' >
```yml
2018-10-04 14:37:37 +01:00
tests:
2019-11-20 07:01:31 -08:00
- text: < code > mode</ code > should be a function.
2019-07-26 05:24:52 -07:00
testString: assert(typeof mode === 'function');
2018-10-20 21:02:47 +03:00
- text: < code > mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])</ code > should equal < code > [6]</ code >
2019-07-26 05:24:52 -07:00
testString: assert.deepEqual(mode(arr1), [6]);
2018-10-20 21:02:47 +03:00
- text: < code > mode([1, 2, 4, 4, 1])</ code > should equal < code > [1, 4]</ code > .
2019-07-26 05:24:52 -07:00
testString: assert.deepEqual(mode(arr2).sort(), [1, 4]);
2018-09-30 23:01:58 +01:00
```
< / section >
## Challenge Seed
< section id = 'challengeSeed' >
< div id = 'js-seed' >
```js
2019-02-26 17:07:07 +09:00
function mode(arr) {
2020-09-15 09:57:40 -07:00
2018-09-30 23:01:58 +01:00
return true;
}
```
< / div >
### After Test
< div id = 'js-teardown' >
```js
2018-10-20 21:02:47 +03:00
const arr1 = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
const arr2 = [1, 2, 4, 4, 1];
2018-09-30 23:01:58 +01:00
```
< / div >
< / section >
## Solution
< section id = 'solution' >
```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;
}
```
< / section >