Sort array of objects by a given property in numbers first, then letters (with numbers having a sub-sort)

I know how to sort by either numbers or letters, not sure how to do both.

sessionStorage.cart
==> "[
{"id":1, "number":1, "other_attributes":"other_values"},
{"id":2, "number":2, "other_attributes":"other_values"},
{"id":"processing", "other_attributes":"other_values"},
{"id":2, "number":1, "other_attributes":"other_values"},
{"id":"deposit", "other_attributes":"other_values"}
]"

I would like to sort the cart by id, where the following applies:

  • first show me all the items where id is an integer
  • then show me all the items where id is a string
  • where id is an integer, if multiple items have the same integer, sort by number
  • where id is a string, sort alphabetically

The end result of the example above should be (after JSON parsing, and setting back to sessionStorage)

==> "[
{"id":1, "number":1, "other_attributes":"other_values"},
{"id":2, "number":1, "other_attributes":"other_values"},
{"id":2, "number":2, "other_attributes":"other_values"},
{"id":"deposit", "other_attributes":"other_values"},
{"id":"processing", "other_attributes":"other_values"},
]"

Answers 1

  • You can use javascript sort function & ternary operator to achieve this. This is basically multilevel sorting.

    Brief explanation

    If we consider id it will take first two id which we are passing and compare them if they are unequal. Here "?" is the condition checker which will check if they are greater or lesser than one another and return 1 or -1. 1 will return ascending order & -1 will return it in descending order. When both id(s) are equal it will check this condition

    a.number>b.number?1:a.number<b.number?-1:0
    

    "0" mean it will return nothing if both are equal.If number are equal you can expand the depth of sorting to "other_attributes" by expanding the ternary operator.

    I have added few more value just to check the gene-unity of the sorting.

    var a = [
    {"id":1, "number":1, "other_attributes":"other_values"},
    {"id":2, "number":3, "other_attributes":"other_values"},
    {"id":2, "number":2, "other_attributes":"other_values"},
    {"id":"processing", "other_attributes":"other_values"},
    {"id":2, "number":1, "other_attributes":"other_values"},
    {"id":"deposit", "other_attributes":"other_values"},
    {"id":1, "number":10, "other_attributes":"other_values"}
    ]
    var b = a.sort(function(a,b){
    
       return a.id.toString() >b.id.toString() ?1:a.id.toString()<b.id.toString()?-1:a.number>b.number?1:a.number<b.number?-1:0
    })
    console.log(b)
    

    CHECK HERE


Related Articles