how to sort strings in javascript numerically

前端 未结 7 1457
一个人的身影
一个人的身影 2021-02-14 12:48

I would like to sort an array of strings (in javascript) such that groups of digits within the strings are compared as integers not strings. I am not worried about signed or fl

7条回答
  •  梦谈多话
    2021-02-14 13:17

    Sorting occurs from left to right unless you create a custom algorithm. Letters or digits are compared digits first then letters.

    However, what you want to accomplish as per your own example (a1, a9, a10) WON'T EVER HAPPEN. That would require you knowing the data before hand and spliting the string in every possible way before applying the sorting.

    One final alternative would be:

    a) break each and every string from left to right whenever is a change from letter to digit and vice versa; & b) then start the sorting on those groups from RIGHT-TO-LEFT. That will be a very demanding algorithm. Can be done!

    Finally, if you are the GENERATOR of the original "text", you should consider NORMALIZING the output where a1 a9 a10 could be outputed as a01 a09 a10. This way you could have full cotnrol of the final version of the algorithm.

    Good luck!

提交回复
热议问题