Skip to content
This repository was archived by the owner on Feb 20, 2019. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ import BitwiseAnd from './BitwiseAnd'
import copyArrayByValue from './copyArrayByValue'
import timeSince from './timeSince'
import first from './first'
import mode from './mode-array'

export {
reverseArrayInPlace,
Expand Down Expand Up @@ -168,4 +169,5 @@ export {
copyArrayByValue,
timeSince,
first,
mode,
}
31 changes: 31 additions & 0 deletions src/mode-array.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
export default mode

/**
* Original Source: https://stackoverflow.com/a/1053865
*
* This method will return the element with the highest occurrence in an array.
*
* @param {Array} array - The array
* @return {*} - The element which has the highest occurrence
*/
function mode(array) {
if (array.length === 0) {
return null
}
const modeMap = {}
let maxEl = array[0]
let maxCount = 1
for (let i = 0; i < array.length; i++) {
const el = array[i]
if (modeMap[el] === undefined) {
modeMap[el] = 1
} else {
modeMap[el]++
}
if (modeMap[el] > maxCount) {
maxEl = el
maxCount = modeMap[el]
}
}
return maxEl
}
23 changes: 23 additions & 0 deletions test/mode.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import test from 'ava'
import {mode} from '../src'

test('mode in an empty array', t => {
const array = []
const expected = null
const actual = mode(array)
t.deepEqual(actual, expected)
})

test('mode in an array of string elements', t => {
const array = ['apple', 'pear', 'banana', 'pear']
const expected = 'pear'
const actual = mode(array)
t.deepEqual(actual, expected)
})

test('mode in an array of int elements', t => {
const array = [1, 2, 3, 4, 3, 5]
const expected = 3
const actual = mode(array)
t.deepEqual(actual, expected)
})