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

How to sort string of numbers in javascript?

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

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.

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

that ?

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