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"
}
6
  • 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. Commented Apr 2, 2016 at 3: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. Commented Apr 2, 2016 at 3:14
  • second link works perfectly Commented Apr 2, 2016 at 3: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}. Commented Apr 2, 2016 at 5: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. Commented Apr 2, 2016 at 5:54

1 Answer 1

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"}},
]*/
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.