Sort String with numbers in javascript ES6

2 years ago23k times

Sort String with numbers in Javascript ES6. If we have a string with injected numeric items at the end, we can slice it and turn into a number in order to sort all the arrays.


const alphanumbers = ['items 1', 'items 19', 'items 13', 'items 12', 'items 14'];
const sortnumbers = alphanumbers.sort((a,b) => {
     return +a.slice(-1) - +b.slice(-1);
}); 
console.log(sortnumbers);  

Add Answer

Add a codeAdd Code
Remove adsremove

Latest codes

view all

Latest Snippets

view all