简体   繁体   中英

How can I sort a list numerically from a specific part of a string

I have this list of links that need to be sorted when they are generated on my page.

The links appear like this

"https://www.dropbox.com/s/###/NF%208975%###" "https://www.dropbox.com/s/###/NF%207600%###"

I then map through them when they are generated onto my page, and create a name based on whats at the end of the link (removing all the junk characters).

Is it possible, without altering the url, to sort them numerically based on the what's at the end of the url. That way when I map through them, they are already ordered.

Like this:

NF%207600%###

NF%208975%###

I've looked through some similar SO questions, but can't seem to find anything relative enough.

You can .map().sort().map() . It may seem bulky, but if you have a lot of URLs, this is more performant since you don't have to perform a number-parsing regex-replace every time you compare a URL to another one. For example, compare the amount of calls when sorting just 5 URLs:

 var array = [ 'https://www.dropbox.com/s/###/NF%208975%###', 'https://www.dropbox.com/s/###/NF%209213%###', 'https://www.dropbox.com/s/###/NF%205346%###', 'https://www.dropbox.com/s/###/NF%201764%###', 'https://www.dropbox.com/s/###/NF%207600%###' ]; function getId(url) { return Number(url.replace(/^.*%(\\d+)%.*$/, '$1')); } function count(func) { function wrapper() { wrapper.count++; return func.apply(this, arguments); } wrapper.count = 0; return wrapper; } var countGetId = count(getId); var sorted = array .map(url => ({ url, number: countGetId(url) })) .sort((a, b) => a.number - b.number) .map(obj => obj.url); console.log('.map().sort().map()') console.log(sorted); console.log('getId called ' + countGetId.count + ' times'); var countGetId = count(getId); var sorted = array.sort((a, b) => countGetId(a) - countGetId(b)) console.log('.sort()') console.log(sorted); console.log('getId called ' + countGetId.count + ' times'); 

So, just do this:

function getId(url) {
  return Number(url.replace(/^.*%(\d+)%.*$/, '$1'));
}

var sorted = array
  .map(url => ({ url, number: getId(url) }))
  .sort((a, b) => a.number - b.number)
  .map(obj => obj.url);

console.log(sorted);

You can use regex to extract the number and then compare by it:

 var urls = ["https://www.dropbox.com/s/###/NF%208975%###", "https://www.dropbox.com/s/###/NF%207600%###"] function extract_number(url) { return Number(url.replace(/.*%(\\d+)%.*/, "$1")) } urls.sort(function(a, b) { if(extract_number(a) < extract_number(b)) { return -1; } if(extract_number(a) > extract_number(b)) { return 1; } return 0; }) console.log(urls); 

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