Policies & Guidelines

SORT_BY_KEY

Sort an array of objects by a key

Description

Sorts an array of objects by the values of the given key.

If the objects do not contain string or number values under the given key, the sort might not behave as expected.

The third parameter can be used to sort in ascending (default) or descending order.

Compared to SORT\_BY\_KEY\_CASE\_SENSITIVE, this function is case insensitive.

Function signature

SORT_BY_KEY(array: Array, key: String, order: String = asc) => Array

Parameter

Description

Array

Array to sort

Key

Key whose value to sort by

Order

Order to sort in ("asc" for ascending, "desc" for descending); defaults to ascending

Examples

array = [
{
"a": 10
},
{
"a": 20,
"b": 1
},
{
"a": 20
},
{
"a": 20,
"b": 2
},
{
"a": 1
},
{
"a": -1,
"b": 2
},
{
"a": 1,
"b": 2
},
{
"a": 3
},
{
"a": -1
}
]
key = "a"
order = "desc"

Formula

Return value

SORT_BY_KEY(array, key)

[{"a":-1,"b":2},{"a":-1},{"a":1},{"a":1,"b":2},{"a":3},{"a":10},{"a":20,"b":1},{"a":20},{"a":20,"b":2}]

SORT_BY_KEY(array, key, order)

[{"a":20,"b":1},{"a":20},{"a":20,"b":2},{"a":10},{"a":3},{"a":1},{"a":1,"b":2},{"a":-1,"b":2},{"a":-1}]