Skip to content

Instantly share code, notes, and snippets.

@kevthanewversi
Last active March 19, 2018 12:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevthanewversi/cae496bc36c7ec100a2dc5afc235aa5a to your computer and use it in GitHub Desktop.
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
//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