Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: solutions for find the most frequent value in as array #130

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
27 changes: 27 additions & 0 deletions solutions/126.js
Original file line number Diff line number Diff line change
@@ -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,
};
13 changes: 13 additions & 0 deletions test/126.js
Original file line number Diff line number Diff line change
@@ -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);
});
});