Skip to content

Sort an array of object literals #21

@travispaul

Description

@travispaul

In my application I have the need to sort an array of object literals by a key, and the key can be any type. For example:

this...

{
  "myArray": [
    {"key": "B", "value": "Buzz"},
    {"key": true, "value": "Baz"},
    {"key": "42", "value": "Flam"},
    {"key": 1, "value": "Bar"},
    {"key": "A", "value": "Foo"},
    {"key": false, "value": "Flub"},
    {"key": 2, "value": "Fizz"},
  ]
}

should sort to to perhaps something like this...

{
  "myArray": [
    {"key": true, "value": "Baz"},
    {"key": false, "value": "Flub"},
    {"key": 1, "value": "Bar"},
    {"key": 2, "value": "Fizz"},
    {"key": "42", "value": "Flam"},
    {"key": "A", "value": "Foo"},
    {"key": "B", "value": "Buzz"},
  ]
}

I am not aware of any way to do this within the library itself but I can think of how to do it outside the library (looping over the array, sorting the keys and attaching the literals into a new array). I am curious if this use case is common enough that it would make sense being in the library itself, or if there was some clever way to use selectors?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions