Skip to content

Instantly share code, notes, and snippets.

@gyaresu
Created March 4, 2015 08:53
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 gyaresu/2e11a6d05ac9b6058fd1 to your computer and use it in GitHub Desktop.
Save gyaresu/2e11a6d05ac9b6058fd1 to your computer and use it in GitHub Desktop.
/*
* Sorting Dictionaries - https://codewars.com
*
* Python dictionaries are inherently unsorted. So what do you do if you need to sort the contents of a dictionary.
*
* In this kata you will create a function that returns a sorted list of (key, value) tuples (Javascript: arrays of 2 items).
*
* The list must be sorted by the value and be sorted largest to smallest.
*
* sortDict({3:1,2:2,1:3}) == [[1,3],[2,2],[3,1]]
* sortDict({1:2,2:4,3:6}) == [[3,6],[2,4],[1,2]]
* */
var dict = {"cat":4,"dog":6,"moose":2, 99: 42};
var keys = Object.keys(dict).sort();
var result = [];
for (var i = 0; i <= keys.length -1; i ++) {
var arr = [];
if (typeof(keys[i]) === 'number')
arr.push(parseInt(keys[i]), dict[keys[i]]);
else
arr.push(keys[i], dict[keys[i]]);
console.log(keys[i], typeof(keys[i]));
result.push(arr);
}
var compare = function (a,b) {
return a[1] - b[1];
};
var x = result.sort(compare).reverse();
console.log(typeof(x[0][0]), result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment