Javascript sort string by last two digit

on

I have order id with combination of string and alpha characters like “30000-T04”, “30000-T10”, “30000-T05”, “30000-T01”, I want to sort this in ascending order. So let’s see how to do that.

To sort an array of strings by the last two digits, you can use the sort() method with a custom comparison function that extracts the last two digits of each string and compares them numerically.

Here’s an example code snippet that demonstrates this:

<code class="">const arr = ["30000-T04", "30000-T10", "30000-T05", "30000-T01"];

arr.sort((a, b) => {
  const aDigits = parseInt(a.slice(-2));
  const bDigits = parseInt(b.slice(-2));
  return aDigits - bDigits;
});

console.log(arr); // ["30000-T01", "30000-T04", "30000-T05", "30000-T10"]</code>

In this example, the sort() method is called on the arr array, with a comparison function that takes two arguments (a and b) representing the elements being compared.

Inside the comparison function, the slice() method is used to extract the last two digits of each string, and the parseInt() function is used to convert them to numbers.

Finally, the function returns the result of subtracting bDigits from aDigits. This means that if a has a higher two-digit number than b, it will be placed before it in the sorted array.

Posted in Javascript by .

About Gowri

I am professional web developer with 8+ years experience. PHP, jQuery, WordPress, Angular and Ionic are my key skills in web development. I am working with strong enthusiastic team with spirit. We provide all web related solution like HTML/CSS development, Web graphic design and Logo.