-2

Given the following function:

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

I am trying to make 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.

2
  • 1
    please add your code. what does not work? Commented Nov 28, 2020 at 16:08
  • 1
    Hello, consider adding your code to get some help. What have you tried so far? Commented Nov 28, 2020 at 16:32

1 Answer 1

0

It might be this:

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

Sign up to request clarification or add additional context in comments.

3 Comments

I like this answer because it's the most precise, but am on the fence due to its complexity and inefficiency.
@expressjs123 I made it more simpler ;)
It's a lot better now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.