Skip to content

Instantly share code, notes, and snippets.

@brito
Created August 3, 2021 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brito/a1e856da353109e8a9ae9259443eb19c to your computer and use it in GitHub Desktop.
Save brito/a1e856da353109e8a9ae9259443eb19c to your computer and use it in GitHub Desktop.
Count top values from a range of values (mode at the top). Useful to detect data anomalies, patterns and degree of variability in values (how different things are, how many nulls, etc)
/* Tally v 1.0 */
function tally (range, limit = 10){
let total = range.length,
values = {}
for (let [k, v] of range) {
k = ('' + k).replace(/\n[\s\S]*/, '…')
values[k] = values[k] ? values[k] + 1 : 1
}
return Object.entries(values)
.sort((a, b) => b[1] - a[1])
.map(
([k, v]) =>
k +
('' + v).padStart(6) +
(Math.floor((100 * v) / total) + '%').padStart(5)
)
.slice(0, limit)
.join('\n')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment