Last active
November 3, 2017 02:17
-
-
Save emafriedrich/245de4910c188fd0a4fe5962fa5f50cd to your computer and use it in GitHub Desktop.
Sort javascript array by difference beetwen elemtents
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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