Skip to content
This repository was archived by the owner on Feb 20, 2019. It is now read-only.

Commit 8bd0450

Browse files
anddagoKent C. Dodds
authored and
Kent C. Dodds
committed
feat(mode): Add array mode function (#222)
1 parent f3aef1a commit 8bd0450

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed

src/index.js

+2
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ import BitwiseAnd from './BitwiseAnd'
8282
import copyArrayByValue from './copyArrayByValue'
8383
import timeSince from './timeSince'
8484
import first from './first'
85+
import mode from './mode-array'
8586

8687
export {
8788
reverseArrayInPlace,
@@ -168,4 +169,5 @@ export {
168169
copyArrayByValue,
169170
timeSince,
170171
first,
172+
mode,
171173
}

src/mode-array.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
export default mode
2+
3+
/**
4+
* Original Source: https://stackoverflow.com/a/1053865
5+
*
6+
* This method will return the element with the highest occurrence in an array.
7+
*
8+
* @param {Array} array - The array
9+
* @return {*} - The element which has the highest occurrence
10+
*/
11+
function mode(array) {
12+
if (array.length === 0) {
13+
return null
14+
}
15+
const modeMap = {}
16+
let maxEl = array[0]
17+
let maxCount = 1
18+
for (let i = 0; i < array.length; i++) {
19+
const el = array[i]
20+
if (modeMap[el] === undefined) {
21+
modeMap[el] = 1
22+
} else {
23+
modeMap[el]++
24+
}
25+
if (modeMap[el] > maxCount) {
26+
maxEl = el
27+
maxCount = modeMap[el]
28+
}
29+
}
30+
return maxEl
31+
}

test/mode.test.js

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import test from 'ava'
2+
import {mode} from '../src'
3+
4+
test('mode in an empty array', t => {
5+
const array = []
6+
const expected = null
7+
const actual = mode(array)
8+
t.deepEqual(actual, expected)
9+
})
10+
11+
test('mode in an array of string elements', t => {
12+
const array = ['apple', 'pear', 'banana', 'pear']
13+
const expected = 'pear'
14+
const actual = mode(array)
15+
t.deepEqual(actual, expected)
16+
})
17+
18+
test('mode in an array of int elements', t => {
19+
const array = [1, 2, 3, 4, 3, 5]
20+
const expected = 3
21+
const actual = mode(array)
22+
t.deepEqual(actual, expected)
23+
})

0 commit comments

Comments
 (0)