需要根据私有变量值对一些芭蕾舞演员对象数组进行排序。我们可以对芭蕾舞演员对象或原始类型数组进行排序吗?有什么功能可以做到吗?
问问题
131 次
2 回答
2
目前没有内置的方法可以对数组进行排序。您可以根据需要实现排序功能。
在 github 中找到了一个可以重用的实现 - https://github.com/chamil321/ballerinaCentralWorkSpace/blob/master/sort/impl.bal。但它适用于整数。我认为它指的是https://central.ballerina.io/chamil/sort包。您可以拉出包装并尝试一下。
于 2018-06-12T13:30:02.280 回答
0
看起来 Ballerina 现在确实支持排序,但您必须完成所有繁重的工作。即使是简单的值类型。唉。
无论如何,这里是一个“按字母顺序排序”的数组,其中包含 json 元素,每个元素都有一个 name 元素 - obvs 也适用于简单的整数或字符串或 woreva 并进行一些调整:
json items = [{ name: "aaa" }, { name: "aab" }];
items.sort(sortItems)
function sortItems(json a, json b) returns int {
// extract character by character numeric representation of string
int[] aname = a.name.toString().toCodePointInts();
int[] bname = b.name.toString().toCodePointInts();
// do character by character comparison
int i = 0;
while (i < aname.length() && i < bname.length()) {
if (aname[i] < bname[i]) { return -1; }
else if (aname[i] > bname[i]) { return 1; }
i += 1;
}
// if all the characters in the shared length is the same
// assume the shorter string should come first
if (aname.length() < bname.length()) { return -1; }
if (aname.length() > bname.length()) { return 1; }
return 0;
}
很高兴得到纠正,并且有一种更简单的本地方式来做到这一点。(数组初始化可能是错误的,没有测试那个位,soz。)
于 2020-10-13T22:03:12.107 回答