Sort JS object of objects(nested)

let tags = {
    "01": {
       contentID: [10, 20],
       occurrences: 1
    },
    "02": {
       contentID: [10, 20],
       occurrences: 1
    },
    "04": {
       contentID: [10, 20],
       occurrences: 3
    },
    "05": {
       contentID: [10, 20],
       occurrences: 6
    }
};

How to sort this in descending order by taking occurrences as base, This is a global variable. So I want to store it in a different object and sort that one with descending order..

3 answers

  • answered 2018-10-11 19:44 Eugene Tsakh

    You can not sort objects, but you can transform it to array of values:

    Object.values(tags).sort((a, b) => b.occurrences - a.occurrences)
    

    The result will be:

    [
      {
        contentID: [10, 20],
        occurrences: 6
      },
      {
        contentID: [10, 20],
        occurrences: 3
      },
      {
        contentID: [10, 20],
        occurrences: 1
      },
      {
        contentID: [10, 20],
        occurrences: 1
      }
    ]
    

    However you can sort your keys separately if you need them as well:

    Object.keys(tags).sort((a, b) => tags[b].occurrences - tags[a].occurrences)
    

    And your result will be an array ['05', '04', '02', '01']

  • answered 2018-10-11 19:46 ashish singh

    Kindly note that objects in javascript dont have any sense of order.

    However you can create and array to hold your result.

    To get it in descending order ,you can do

    Object.values(tags).sort((a,b) => b.occurrences - a.occurrences)

  • answered 2018-10-11 20:28 Scott Sauyet

    Other suggestions to think about this as an array are probably sound. It's not a good idea to think of Javascript objects as ordered, even though there is a key-ordering specification. But, if you want to keep the results in the same format, you can do so, and still end up sorting the keys:

    let tags = {"01": {"contentID": [10, 20], "occurrences": 1}, "02": {"contentID": [10, 20], "occurrences": 1}, "04": {"contentID": [10, 20], "occurrences": 3}, "05": {"contentID": [10, 20], "occurrences": 6}}
    
    const sorted = Object.entries(tags).sort(([, {occurrences: a}], [, {occurrences: b}]) => b - a)
      .reduce((a, [k, v]) => Object.assign(a, {[k]: v}), {})
    
    console.log(sorted)

    I can't see what this is really good for, though. The only place you can see a difference in behavior is if you use something like Object.keys, Object.values, or Object.entries on it, again creating arrays.