Home > Blockchain >  Javascript sort mixed alphanumeric array - letters ascending, numbers descending
Javascript sort mixed alphanumeric array - letters ascending, numbers descending

Time:03-30

I have an alphanumeric array that I need to sort by alphabet ascending and then by number descending, the array is a as follows:

[A1, A4, A2, A3, C2, C4, C3, B3, B5, B4]

How do I sort the array using JavaScript, so it looks like:

[A4, A3, A2, A1, B5, B4, B3, C4, C3, C2]

I have tried:

arr.sort() 

but that only sorts it alphabetically and numerically ascending, giving me:

[A1, A2, A3, A4, B3, B4, B5, C2, C3, C4]

CodePudding user response:

If you have always a single letter, you could sort by the numerical rest and by the first letter.

const
    array = ['A1', 'A4', 'A2', 'A3', 'C2', 'C4', 'C3', 'B3', 'B5', 'B4'];

array.sort((a, b) => a[0].localeCompare(b[0]) || b.slice(1) - a.slice(1));

console.log(...array);

If you have more than one letter, you could take a regular expression and get only digits and non digits, separated into an object.

const
    getValues = string => ({
        letters: string.match(/\D /)[0],
        digits: string.match(/\d /)[0]
    }),
    array = ['A1', 'A4', 'A2', 'A3', 'C2', 'C4', 'C3', 'B3', 'B5', 'B4'];

array.sort((a, b) => {
    const [aa, bb] = [a, b].map(getValues);

    return aa.letters.localeCompare(bb.letters)
        || bb.digits - aa.digits;
});

console.log(...array);

CodePudding user response:

You need to write a custom function that separate string and numeric parts from the value and compares them one by one:

const array = ["A1", "A4", "A2", "A3", "C2", "C4", "C3", "B3", "B5", "B4"];
array.sort(function(a, b) {
  let astr = a.slice(0, 1);
  let bstr = b.slice(0, 1);
  let aint = Number(a.slice(1));
  let bint = Number(b.slice(1));
  return astr.localeCompare(bstr) || bint - aint;
});
console.log(array);

CodePudding user response:

array.sort take a callback where you can define the condition on how you compare two elements in your array

to perform your need an idea can be to return the comparison of second character if first one is identical

var data = ['A1', 'A4', 'A2', 'A3', 'C2', 'C4', 'C3', 'B3', 'B5', 'B4'];
var result = data.sort((a, b) => {
  if (a === b) {
     return 0;
  }
  if (a[0] === b[0]) {
    return (a[1] > b[1]) ? -1 : 1;
  }
  return (a > b) ? 1 : -1;
});
console.log(result);

  • Related