2

How would you sort an associative array by the values properties? The value itself is an object with multiple properties and one of the properties of the object is a string. I want to be able to rearrange the array alphabetically by the string. Is that possible?

I tried looking for answers in several places including here: How to sort an array of associative arrays by value of a given key in PHP?

How to sort an associative array by its values in Javascript?

How to sort an (associative) array by value?

I don't think those answered my question... not least not in a way I understand. Any help would be appreciated. Example:

Object = {
    1: obj.prop = "C", 
    5: obj.prop = "A, 
    3: obj.prop = "B
}

I would want:

Object = {
    5: obj.prop = "A",
    3: obj.prop = "B",
    1: obj.prop = "C"
}
Community
  • 1
  • 1
ProgrammingGodJK
  • 207
  • 1
  • 3
  • 10
  • 2
    (1) JavaScript objects are *somewhat* like "associative arrays" but they really aren't quite the same, and (2) properties in objects have no particular order; "sorting" doesn't make sense. – Pointy Apr 02 '16 at 03:13
  • 1
    You can use `Object.keys()` to extract an *array* of property names, sort that however you like, and then iterate through it to visit object properties in that order. – Pointy Apr 02 '16 at 03:14
  • second link works perfectly – juvian Apr 02 '16 at 03:19
  • @John Object properties can start with a digit as long as they are strings. `{"0":1}` is a valid object and so is `{"0":1,"00":1}`. – RainingChain Apr 02 '16 at 05:12
  • What was it about the other questions and answers that you did not understand? If you have a separate question about those answers, then post that question; otherwise, this is a duplicate. –  Apr 02 '16 at 05:54
  • I'm not sure, maybe I'm just not smart enough but the other answers didn't feel applicable or I just couldn't discern what information I needed to resolve my issue. – ProgrammingGodJK Apr 04 '16 at 18:01

1 Answers1

0

In Javascript, associative arrays (object) don't have an order.

This means it will be impossible to store the result in an object. Instead, you can store it in a array of {key,value} object.

var obj = {
    "1":{prop:"C"},
    "5":{prop:"A"},
    "3":{prop:"B"},
}

var res = [];
for(var i in obj){
    res.push({
        key:i,
        value:obj[i]
    });
}   

res.sort(function(a,b){
    return a.value.prop > b.value.prop ? -1 : 1;
});

/*res == [
    {key:5,value:{prop:"A"}},
    {key:3,value:{prop:"B"}},
    {key:1,value:{prop:"C"}},
]*/
RainingChain
  • 7,397
  • 10
  • 36
  • 68
  • I think in the sort, the ternary operator should be a.value.prop > b.value.prop ? 1 : -1; instead but you gave me what I needed to figure it out. Thank you so much! – ProgrammingGodJK Apr 04 '16 at 17:59