排序月份(带字符串)算法 [英] Sort months ( with strings ) algorithm
本文介绍了排序月份(带字符串)算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个月份的数组:
["January", "March", "December" , "October" ]
我想像这样排序:
["January", "March", "October", "December" ]
我目前正在以"if/else"可怕的级联方式思考,但是我想知道是否还有其他方法可以做到这一点.
I'm currently thinking in a "if/else" horrible cascade but I wonder if there is some other way to do this.
糟糕的是,我只需要使用"string"(即,不使用Date对象或类似的东西)
The bad part is that I need to do this only with "string" ( that is, without using Date object or anything like that )
什么是好的方法?
推荐答案
如果我可以提供自定义排序顺序,则可以创建一个定义正确顺序的列表:
If I had a way to supply a custom sorting order, I'd create a list defining the correct order:
correct = List("January", "February", "March", ...)
然后按该列表中的位置进行排序,例如:
And then sort by the position in that list, something like:
toSort.sort(a, b) => compare(correct.index(a), correct.index(b))
这篇关于排序月份(带字符串)算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文