how do I sort a dictionary by key like
dict[\"word_21\"] = \"Hello Java\";
dict[\"word_22\"] = \"Hello World\";
dict[\"word_11\"] = \"Hello Javascript\";
Try this
var sorted = [];
for(var key in dict) {
sorted[sorted.length] = key;
}
sorted.sort();
Sorting dict
on its keys and writing it back to the object does not make sense to me, but here it goes:
function sortOnKeys(dict) {
var sorted = [];
for(var key in dict) {
sorted[sorted.length] = key;
}
sorted.sort();
var tempDict = {};
for(var i = 0; i < sorted.length; i++) {
tempDict[sorted[i]] = dict[sorted[i]];
}
return tempDict;
}
dict = sortOnKeys(dict);
If you just want to sort keys in an object, the following is fine (its a one liner)
/**
* (typescript) returns the given object with keys sorted alphanumerically.
* @param {T} obj the object to sort
* @returns {T} the sorted object
*/
const sort = <T extends object>(obj: T): T => Object.keys(obj).sort()
.reduce((acc, c) => { acc[c] = obj[c]; return acc }, {}) as T
or the same in javascript
/**
* (javascript) returns the given object with keys sorted alphanumerically.
* @param {T} obj the object to sort
* @returns {T} the sorted object
*/
const sort = (obj) => Object.keys(obj).sort()
.reduce((acc, c) => { acc[c] = obj[c]; return acc }, {})
A javascript object, here used as a key-value-map (called "dictionary"), has no order; ie. you can't sort it.
You would need an array for that, e.g.
[
{id: "word_11", entry:"Hello Javascript"},
{id: "word_21", entry:"Hello Java"},
{id: "word_22", entry:"Hello World"},
]
then you could sort that by id or by entry. You might use your id-sort-algorithm for that.
Or you could use an array of your keys to sort, next to the unsorted data structure. This might be the best (efficient) and simplest approach:
var dict = {
"word_21": "Hello Java",
"word_22": "Hello World",
"word_11": "Hello Javascript"
}; // init (like your example)
var keys = Object.keys(dict); // or loop over the object to get the array
// keys will be in any order
keys.sort(); // maybe use custom sort, to change direction use .reverse()
// keys now will be in wanted order
for (var i=0; i<keys.length; i++) { // now lets iterate in sort order
var key = keys[i];
var value = dict[key];
/* do something with key & value here */
}
@Amberlamps nice solution works most of the time. But, the OP is correct that there are splitting issues with certain keys. The default behavior of sort() in javascript is to use string Unicode code points to determine the order of the elements. For example, the following keys will not get sorted correctly using @Amberlamps method:
canvas_2_1/15/2018__2:55:20_PM
canvas_24_1/15/2018__2:55:20_PM
But we can customize the sort method taking advantage of the fact that sort() accepts an optional argument which is a function that compares 2 elements of the array.
By customizing the sort logic of the compare function and passing it to the sort() method the keys above get sorted correctly:
sorted.sort(function(a, b) {
a = parseInt(get_between(a, 'canvas_', '_'));
b = parseInt(get_between(b, 'canvas_', '_'));
if (a > b) {
return 1;
}
if (b > a) {
return -1;
}
return 0;
});
In this case I'm using the following get_between method:
function get_between(str, char_a, char_b) {
res = str.split(char_a).pop().split(char_b).shift();
return(res)
}
Th point is, if you have tricky keys (which may or may not be "proper" use of dict) you can adapt the sort function to still sort correctly.
Simply put, the dictionary type does not have a keys() method, while the Object type does. You can pass the Object.keys() method an iterable and get the keys back as a list which has a .sort() method.
Object.keys({r:2,d:2,c:3,p:0})
// returns ["r", "d", "c", "p"]
Object.keys({r:2,d:2,c:3,p:0}).sort()
// returns ["c", "d", "p", "r"]
Object.keys([6,7,8,9])
// returns ["0", "1", "2", "3"]
And finally, let's jsFiddle the OP's code.
Update: Bergi's answer had too much going on and I totally missed the "good answer" part. I didn't even notice he did the same thing I did in my jsFiddle.