Skip to content

Instantly share code, notes, and snippets.

@zkavtaskin
Last active January 8, 2022 23:10
Show Gist options
  • Save zkavtaskin/b4060385e9988f1b63fbcd9a399715d8 to your computer and use it in GitHub Desktop.
Save zkavtaskin/b4060385e9988f1b63fbcd9a399715d8 to your computer and use it in GitHub Desktop.
Histogram function in JavaScript
/***
* Histogram "bins" numbers in the array X in to group ranges.
* Example usage histogram([1,5,2,4,2,5,2,3,1], 2) would return back [5,2,2] where bin ranges are [1-2, 3-4, 5-6] as bin range is 2
* Example usage histogram([1,5,2,4,2,5,2,3,1], 1) would return back [2,3,1,1,2] where bin ranges are [1,2,3,4,5] as bin range is 1
*/
function histogram(X, binRange) {
//inclusive of the first number
var max = Math.max(...X);
var min = Math.min(...X);
var len = max - min + 1;
var numberOfBins = Math.ceil(len / binRange);
var bins = new Array(numberOfBins).fill(0);
//-min to normalise values for the array
X.forEach((x) => bins[Math.floor((x-min) / binRange)]++);
return bins;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment