简体   繁体   中英

Sort Array of String by Index - JavaScript

How can I sort my array of strings by index either ascending or descending:

var arr = ['heck', 'yeah', 'soon', 'greet'];

return arr.slice(0, 10).sort((a, b) => b > a).map(function(tag){
   console.log(tag);
});

I can't use length here cause by default it will sort it via length.

Any idea?

thanks!

The sort() method sorts the elements of an array in place. The default sort order is according to string Unicode code points. So you can use

acs:

arr.sort()

desc:

arr.sort(); 
arr.reverse();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM