0

The problem I face is that my array is not indexed by 0,1,2,3 etc. Its indexes are an id 0654, 3423, 7543 etc... so for example:

var obj = {};
obj["0654"] = { "Name" : "Tony" };
obj["3423"] = { "Name" : "Fred" };
obj["7543"] = { "Name" : "Dave" };

I am looking for a way to sort these by the Name key. But I keep getting an not a function error. Not too sure what I am doing wrong. I am using this code to sort it:

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;
    });
}

Doing this:

obj.sortByProp("Name");

Any guidance or the best way to approach this would be greatly appreciated... If this is a duplicate from another post, my apologies please point me in the right direction because I searched for this scenario all over and could not find the solution? Also, if you could tell me why this doesn't work too I can then understand objects a little better.

Paul
  • 1,527
  • 2
  • 16
  • 24
  • 6
    Your obj is not an array – mplungjan Jul 17 '15 at 19:57
  • 6
    Objects don't have a sort order... – tymeJV Jul 17 '15 at 19:57
  • you want them sorted into a new array with index 0 being dave? etc..? – floor Jul 17 '15 at 20:00
  • [This](http://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript) pretty much covers what you were looking for – TheHuman Wall Jul 17 '15 at 20:01
  • you can't re-order numeric object properties, only alpha keys will stay custom ordered (in insertion order) – dandavis Jul 17 '15 at 20:13
  • I see, this is great info. I definitely overlooked this. Now that I am not trying to sort an array but objects of an object. I need to write some sort of function to do it. But I would like to rearrange the original object. How do you convert it to an array then back in a function? – Paul Jul 17 '15 at 20:25

1 Answers1

0

UnderscoreJS is your best friend!

_.sortBy(obj, 'Name');

Try it yourself.

SDekov
  • 9,276
  • 1
  • 20
  • 50
  • This looks real good and I didi try this method but it won't work in my setup? Not too sure why. I didn't see DanDavis's comment but I do want to affect the original object. – Paul Jul 17 '15 at 20:26