简体   繁体   中英

How to sort string of numbers in javascript?

Given the following function:

function sortFunction(str) {
  // return srt
}
console.log(sortFunction("20 150 2343 20 9999"));

what I am trying to do is a function that returns an string with the same sequence of numbers, but sorted by the sum of its characters . so I should get ("20 150 2343 9999") What happens with "20"? If 2 numbers are of the same value, I need to sort them as strings.

Any insight would be appreciated.

that?

 const sortFunction = str => /* keep only numbers groups */ str.match(/\d+/g) /* ascending sort */.sort((a,b)=>+ab) /* remove duplicates */.filter((c,i,t)=>.i||t[i-1];=c) // 1st OR.= prev /* rebuild a string */;join(' '); console.log(sortFunction("20 150 2343 20 9999")); // 20 150 2343 9999

const sortFunction = (str) => {
  return str.split(' ').sort((a, b) => parseInt(b.split('').reduce((acc, cur) => acc + parseInt(cur), 0)) - parseInt(a.split('').reduce((acc, cur) => acc + parseInt(cur), 0)));
}

will sort by number in descending order of char sum.

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