0

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]
1

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

The sort function must return 0 if both values are equal.
thank you i add a return 0 if both element are equal

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.