Ignoring original sort order
You can implement it by replacing the comprehension with std.foldl()
, do note though the ordering issue:
local arr = [
{ name: "a", value: 4321 },
{ name: "b", value: 555 },
{ name: "c", value: 0 },
{ name: "a", value: 1234 },
];
// Use foldl to iterate from array, can't use comprehension because of dup fields
local map = std.foldl(function(x, y) x { [y.name]: y }, arr, {});
// Re-convert map to array, note that it'll not respect original order
// but fields' (ie 'name' key)
[ map[x] for x in std.objectFields(map)]
Keeping original sort order
If you need to keep original sort order in output array, you can then add an _idx
field to use in a final sort()
:
local arr = [
{ name: "a", value: 4321 },
{ name: "b", value: 555 },
{ name: "c", value: 0 },
{ name: "a", value: 1234 },
];
// Overload array elements with there index (`_idx` field)
local idxArray = std.mapWithIndex(function(i, x) x { _idx:: i }, arr);
// Use foldl to iterate from array, can't use comprehension because of dup fields
local map = std.foldl(function(x, y) x { [y.name]: y }, idxArray, {});
// Re-convert map to array, it'll keep original order via added _idx field
std.sort([map[x] for x in std.objectFields(map)], function(e) e._idx)