es-next-tools
Version:
A comprehensive utility library for JavaScript and TypeScript that provides a wide range of functions for common programming tasks, including mathematical operations, date manipulations, array and object handling, string utilities, and more.
19 lines (18 loc) • 580 B
JavaScript
/**
* Calculates the mode(s) of a list of numbers.
* @param {...number[]} numbers - The numbers to calculate the mode of.
* @returns {number[]} An array of the most frequent numbers (modes).
* @example
* mode(1, 2, 2, 3, 4); // [2]
*/
export function mode(...numbers) {
const frequency = {};
let maxFreq = 0;
for (let i = 0; i < numbers.length; i++) {
frequency[i] = (frequency[i] || 0) + 1;
maxFreq = Math.max(maxFreq, frequency[i]);
}
return Object.keys(frequency)
.filter(n => frequency[+n] === maxFreq)
.map(Number);
}