Skip to content
Advertisement

sorting JavaScript array that contains version numbers and letters (where letters represents a numerical value)

Say I have an array like this:

input = [
    "1.1",
    "1.c",
    "1.b",
    "1",
    "D",
    "b",
    "4",
    "2.1.2",
    "5.1",
    "3",
    "2.a.1"
]

What would be the best way to sort this and get result like this:

sorted = [
    "1",
    "1.1",
    "1.b",
    "1.c",
    "b",
    "2.a.1",
    "2.1.2",
    "3",
    "4",
    "D",
    "5.1"
]

Here, to sort, consider:

‘a’ or ‘A’ is equivalent to 1,

‘b’ or ‘B’ is equivalent to 2,

and so on.

The array contains numbers and letters only, no symbols.

So far I have tried:

input = ["1", "1.1", "1.b", "1.c", "b", "2.a.1", "2.1.2", "3", "4", "D", "5.1"]
console.log(input.sort((a, b) => a.localeCompare(b)));

Does not give me the desired result. Need help on it. Any suggestions, please?

Advertisement

Answer

You can do it using a function to transform the inputs and the sort function. Here is how I did it:

input = [
    "1.1",
    "1.c",
    "1.b",
    "1",
    "D",
    "b",
    "4",
    "2.1.2",
    "5.1",
    "3",
    "2.a.1"
]

function convert(el){
 const nums = el.split(".");
 return nums.map(n => {
    if(n.match(/[A-z]/)){ 
      return n.toLowerCase().charCodeAt(0) - 96;
    }
    return n;
  }).join(".");
}

input.sort((a,b) => {
  const convA = convert(a);
  const convB = convert(b);
  return convA.localeCompare(convB);
})

console.log(input);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement