Can someone walk me through this exercise? Write a JavaScript program to find the most frequent item of an array.
I don't understand why there needs to have two for loops.
There is no need for two loops, except for author choice.
Why the need for
mfandm. Seems a bit confusing.
They are necessary for the solution that the author has chosen.
m is the count of the current value being tested.
mf is the current maximum frequency to test m against and make a decision if the current element being tested is more frequent than the previously most frequent.
Is there other way of solution on this?
Sure, plenty. Here is another one that takes things a step further.
function getMostFrequentElement(inputArg) {
var type = typeof inputArg,
length,
mostFrequent,
counts,
index,
value;
if (inputArg === null || type === 'undefined') {
throw TypeError('inputArg was "null" or "undefined"');
}
mostFrequent = [];
if (type === 'function' || !Object.prototype.hasOwnProperty.call(inputArg, 'length')) {
mostFrequent[0] = inputArg;
mostFrequent[1] = 1;
} else {
counts = {};
length = inputArg.length;
for (index = 0; index < length; index += 1) {
value = inputArg[index];
type = typeof value;
counts[type] = counts[type] || {};
counts[type][value] = (counts[type][value] || 0) + 1;
if (!mostFrequent.length || counts[type][value] >= mostFrequent[1]) {
mostFrequent[0] = value;
mostFrequent[1] = counts[type][value];
}
}
}
return mostFrequent;
}
function logMostFrequentElement(inputArg) {
var mostFrequentElement,
element,
text;
try {
mostFrequentElement = getMostFrequentElement(inputArg)
if (mostFrequentElement.length) {
element = mostFrequentElement[0];
if (typeof element === 'string') {
element = '"' + element + '"';
}
text = element + ' ( ' + mostFrequentElement[1] + ' times )';
} else {
text = 'No elements';
}
} catch (e) {
text = e.message;
}
document.getElementById('out').appendChild(document.createTextNode(text + '\n'));
}
logMostFrequentElement();
logMostFrequentElement(1);
logMostFrequentElement(true);
logMostFrequentElement(function (x) { return x; });
logMostFrequentElement(/ab/g);
logMostFrequentElement([]);
logMostFrequentElement([1, 2]);
logMostFrequentElement([1, NaN, 2, NaN, 'NaN']);
logMostFrequentElement([1, Infinity, 2, Infinity, 'Infinity', -Infinity]);
logMostFrequentElement(['1', '2', 1, '2', 2]);
logMostFrequentElement([3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3]);
logMostFrequentElement([34, 'ab', 'ab', 'ab', 21, 34, 'ab', 34, 'ab', 21, 45, 99, 34]);
logMostFrequentElement('Also works with strings.');