diff --git a/snippets/mostFrequent.md b/snippets/mostFrequent.md new file mode 100644 index 000000000..3d2d08876 --- /dev/null +++ b/snippets/mostFrequent.md @@ -0,0 +1,23 @@ +--- +title: mostFrequent +tags: array,intermediate +--- + +Returns the most frequent element in an array. + +Use `Array.prototype.reduce()` to map unique values to an object's keys, adding to existing keys every time the same value is encountered. +Use `Object.entries()` on the result in combination with `Array.prototype.reduce()` to get the most frequent value in the array. + +```js +const mostFrequent = arr => + Object.entries(arr.reduce( + (a, v) => { + a[v] = a[v] ? a[v] + 1 : 1; + return a; + }, {} + )).reduce((a, v) => v[1] >= a[1] ? v : a, [null, 0])[0]; +``` + +```js +mostFrequent(['a', 'b', 'a', 'c', 'a', 'a', 'b']); // 'a' +``` diff --git a/test/mostFrequent.test.js b/test/mostFrequent.test.js new file mode 100644 index 000000000..b2097eda0 --- /dev/null +++ b/test/mostFrequent.test.js @@ -0,0 +1,8 @@ +const {mostFrequent} = require('./_30s.js'); + +test('mostFrequent is a Function', () => { + expect(mostFrequent).toBeInstanceOf(Function); +}); +test('returns the most frequent value', () => { + expect(mostFrequent(['a', 'b', 'a', 'c', 'a', 'a', 'b'])).toBe('a'); +});