I would like to compute a numeric value for strings containing only /[a-z0-9]/i
(ignore case). Later, I want to use this value for sorting rows. For this post, I am ignoring number also.
My thinking was, that I can define an alphabet like 0123456789a...z
and compute a sortable value by summing up the indexes of each character found, like this (pseudo code but should work in ES6):
const alpha = 'abcdefghijklmnopqrstuvwxzy'.split('');
function easySort(myString) {
myString = myString.toLowerCase();
let sortableValue = 0;
for (let i = 0; i < myString.length; i++) {
sortableValue += alpha.indexOf(myString.charAt(i)) + 1; // to avoid 0
}
return sortableValue;
};
Simple example (assuming indexes a=1, b=2, ..):
let arr = ['abc', 'ab', 'abd', 'aba'];
let ordered = arr.sort((a, b) => easySort(a) - easySort(b));
// ordered now is ['ab', 'aba', 'abc', 'abd']
The question is, is this a good approach for strings from that alphabet? Are there cases when this would not work the intended way?
I am not asking for improvements of the code but rather the algorithm and whether it may behave unexpected for certain values (by that I do not mean illegal values).