I am currently dealing with an issue where my array does not have traditional numerical indexes (0, 1, 2, 3, etc.), but rather uses IDs like 0654, 3423, 7543, and so on. For example:
var obj = {};
obj["0654"] = { "Name" : "Tony" };
obj["3423"] = { "Name" : "Fred" };
obj["7543"] = { "Name" : "Dave" };
I am trying to find a way to sort these objects by their "Name" key, but I keep encountering an error stating that it is not a function. I am using the following sorting code:
Array.prototype.sortByProp = function(p){
return this.sort(function(a,b){
return (a[p].toLowerCase() > b[p].toLowerCase()) ? 1 : (a[p].toLowerCase() < b[p].toLowerCase()) ? -1 : 0;
});
}
When attempting to run the sorting function with:
obj.sortByProp("Name");
Any advice or suggestions on the best approach would be greatly appreciated. If this question has been asked before, please direct me accordingly as my search for a solution to this specific scenario has so far been unsuccessful. Additionally, understanding why this method is not working will help me gain a better grasp of working with objects.