simple-statistics
Version:
31 lines (29 loc) • 767 B
JavaScript
/**
* Sort an array of numbers by their numeric value, ensuring that the
* array is not changed in place.
*
* This is necessary because the default behavior of .sort
* in JavaScript is to sort arrays as string values
*
* [1, 10, 12, 102, 20].sort()
* // output
* [1, 10, 102, 12, 20]
*
* @param {Array<number>} x input array
* @return {Array<number>} sorted array
* @private
* @example
* numericSort([3, 2, 1]) // => [1, 2, 3]
*/
function numericSort(x) {
return (
x
// ensure the array is not changed in-place
.slice()
// comparator function that treats input as numeric
.sort(function (a, b) {
return a - b;
})
);
}
export default numericSort;