Skip to content

Instantly share code, notes, and snippets.

@emafriedrich
Last active November 3, 2017 02:17
Show Gist options
  • Save emafriedrich/245de4910c188fd0a4fe5962fa5f50cd to your computer and use it in GitHub Desktop.
Save emafriedrich/245de4910c188fd0a4fe5962fa5f50cd to your computer and use it in GitHub Desktop.
Sort javascript array by difference beetwen elemtents
function sortByDifference (value, arr) {
return arr.sort(function (x, y) {
let difx = Math.abs(parseFloat(x) - value);
let dify = Math.abs(parseFloat(y) - value);
if (difx < dify) return -1;
if (difx == dify) return 0;
return 1;
});
}
let array = [2,4,23,33];
sortByDifference(10, array); // [ 4, 2, 23, 33 ]
sortByDifference(90, array); // [ 33, 23, 4, 2 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment