We have two sets of string ID, one is starting with special string like CA-101010, CA-101020. The other set is more diversified like NNN-ABC123, BC123456 etc. We would like sort it by CA first and then rest or CA last. For example the sort order is:
BA123456
NNN-ABC123
CA-101010
CA-101020
Or
CA-101010
CA-101020
BA123456
NNN-ABC123
How can we do this? Diana mentioned custom compare function? Thanks!
@jianmei.fan thanks for bringing this question here! So one of the ideas of how we can make such sorting possible is to prompt the user who opens ‘Custom Sort’ dialog for a compare function, and sort the values based on its outcome. Would it be convenient for users, or are there any other options to do this that people are used to?
@skalkin please share your thoughts too
@donufriienko I am not aware any good way to do this directly. Interesting to learn how this compare function. Do you have an example to show how this might be done? It will be cool if you can do it. Thanks!
@jianmei.fan, while we support a few different ways of string sorting out-of-the-box (such as alphanumerical or natural), the kind of sorting you want appears quite specific, so indeed custom comparison functions is the way to go. Here is the post that explains how to use them: JavaScript API updates
I also went ahead and created a script for your particular use case:
// Providing custom comparer function
let column = DG.Column.fromList(DG.TYPE.STRING, 'id',
['BA123456', 'NNN-ABC123', 'CA-101010', 'CA-101020']);
column.valueComparer = (s1, s2) => {
let c1 = s1.startsWith('CA');
let c2 = s2.startsWith('CA');
if (c1 && c2 || !c1 && !c2) return s1.localeCompare(s2);
return c1 ? 1 : -1;
}
// in case you need the order. prints BA123456, NNN-ABC123, CA-101010, CA-101020
let order = column.getSortedOrder();
grok.shell.info(Array.from(order).map((i) => column.get(i)).join(', '));
// double-click on the header to sort
grok.shell.addTableView(DG.DataFrame.fromColumns([column]));