arrayssortingreasonbucklescript

how can I alphabetically sort an array of records where a record has a name: string field?


let items = [| {name: "b"}, {name: "c"}, {name: "a"}|];

// expected output

[| {name: "a"}, {name: "b"}, {name: "c"}|];

Was thinking about using Belt.SortArray.stableSortBy but requires an int.


Solution

  • String.compare happens to return an int, so you can just use that:

    let items = [| {name: "b"}, {name: "c"}, {name: "a"}|];
    
    let sorted = Belt.SortArray.stableSortBy(items, (a, b) => String.compare(a.name, b.name));