Last active
March 19, 2018 12:15
-
-
Save kevthanewversi/cae496bc36c7ec100a2dc5afc235aa5a to your computer and use it in GitHub Desktop.
Some nifty JS script that can be used to sort a dictionary <python> or rather Object <javascript> by one of the values in the Object
This file contains hidden or 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
//init a dict with key value pairs. The values in my case are arrays. That can be changed | |
var dict = { | |
"x": [1, 3], | |
"y": [6, 90], | |
"z": [9, 16], | |
"a": [5, 3], | |
"b": [7, 9], | |
"c": [11, 3], | |
"d": [17, 3], | |
"t": [3, 10] | |
}; | |
// Create items array | |
var items = Object.keys(dict).map(function(key) { | |
return [key, dict[key]]; | |
}); | |
// Sort the array based on the second element | |
items.sort(function(first, second) { | |
return second[1][0] - first[1][0]; | |
}); | |
// Create a new array with only the first 8 items | |
console.log(items.slice(0, 8)); | |
alert(items.slice(0, 8)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment