diff --git a/solutions/126.js b/solutions/126.js new file mode 100644 index 0000000..b0c1879 --- /dev/null +++ b/solutions/126.js @@ -0,0 +1,27 @@ +// Satish Jhanwer +// Find the most frequent value in an array + +const solution = (arr) => { + // Creating Hash Map based on the unique value from the input array. + const myMap = arr.reduce((result, key) => { + result[key] = key in result ? result[key] + 1 : 1; + return result; + }, {}); + + // Defined the maxCount and resultant value which is most frequent + let maxCount = 0; + let result = -1; + const entries = Object.entries(myMap); + for (const [key, value] of entries) { + if (maxCount < value) { + result = key; + maxCount = value; + } + } + // Most frequent value in an array. + return parseInt(result, 10); +}; + +module.exports = { + solution, +}; diff --git a/test/126.js b/test/126.js new file mode 100644 index 0000000..31d7339 --- /dev/null +++ b/test/126.js @@ -0,0 +1,13 @@ +const expect = require('chai').expect; +let solution = require('../solutions/126').solution; + +describe('Find the most frequent value in an array', () => { + it('should return 3 as most frequent value for [1,2,3,3].', () => { + const result = solution([1, 2, 3, 3]); + expect(result).to.equal(3); + }); + it('should return 2 as most frequent value for [1,2,3,3,4,2,2].', () => { + const result = solution([1, 2, 3, 3, 4, 2, 2]); + expect(result).to.equal(2); + }); +});