[英]How to sort string of numbers in javascript?
Given the following function:给定以下 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 .我想做的是一个 function ,它返回一个具有相同数字序列的字符串,但按其字符的总和排序。 so I should get ("20 150 2343 9999") What happens with "20"?
所以我应该得到(“20 150 2343 9999”)“20”会发生什么? If 2 numbers are of the same value, I need to sort them as strings.
如果 2 个数字具有相同的值,我需要将它们排序为字符串。
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.将按数字按字符和的降序排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.