Warm tip: This article is reproduced from serverfault.com, please click

其他-如何在JavaScript中对数字字符串进行排序?

(其他 - How to sort string of numbers in javascript?)

发布于 2020-11-28 16:05:44

赋予以下功能:

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

我要尝试做的是一个函数,该函数返回具有相同数字序列的字符串,但按其字符的总和排序所以我应该得到(“ 20 150 2343 9999”)“ 20”会发生什么?如果2个数字的值相同,则需要将它们按字符串排序。

任何见识将不胜感激。

Questioner
Kawazaki
Viewed
0
Mister Jojo 2020-11-29 01:29:40

那 ?

const sortFunction = str =>
/* keep only numbers groups  */ str.match(/\d+/g)
/* ascending sort           */    .sort((a,b)=>+a-b)
/* 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