Home > Enterprise >  sorting JavaScript array that contains version numbers and letters (where letters represents a numer
sorting JavaScript array that contains version numbers and letters (where letters represents a numer

Time:01-19

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?

CodePudding user response:

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);

CodePudding user response:

Here is a simplified version of @mgm793's sort function:

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

function conv(str){
 return str.toLowerCase().replace(/[a-z]/g,m=>m.charCodeAt(0)-96)
}

input.sort((a,b) =>conv(a).localeCompare(conv(b)))

console.log(input);

  • Related