Home >Web Front-end >JS Tutorial >Codewars - Descending Order

Codewars - Descending Order

Linda Hamilton
Linda HamiltonOriginal
2025-01-05 10:39:43508browse

Salutations.

Codewars - Descending Order

I'm posting Codewars challenges and my thought process in this series. I'm using JS and Node 18 whenever possible. Just for the sake of clarity, I'm making fair use of them.

Onto the next challenge from Codewars. In this one, we are tasked with developing a function that takes any integer as input. We have to order the digits from highest to lowest.

I start with this thought:

"Ok, I'll need to split the digits somehow. Maybe I should turn the integer to string first. Then split digits. Then order, then concatenate all, then revert to integer"

And so, it starts with a template:

function descendingOrder(n){

 // stringify
  number = n.toString();

 // split digits
  array = new Array(number.length);
  // code that fills array with digits {}

 //sort
  array.sort()

 // concatenate digits
  reverse = array.join('');

 // back to integer
  n = Number.parseInt(reverse);

  return n;
}

Much letters, such bore. And still not functional. So, what else do we need? Well, a loop that places the digits in the array for starters:

 // split digits
  array = new Array(number.length);
  for(i=0 ; i<number.length ; i++){
    array[i] = number.at(i);
  }

That should do it. Right?

Codewars - Descending Order

Nope. One tiny little detail. The devil is in the details. And so are bugs. The sort function orders in ascending fashion by default. We need to "revert polarity". In essence, we need this. The default behavior is like this:

(a, b) => a - b

And we need:

(a, b) => b - a

All the ingredients combined:

function descendingOrder(n){
  number = n.toString();
  array = new Array(number.length);
  for(i=0;i<number.length;i++){
    array[i] = number.at(i);
  }
  array.sort((a,b)=>b-a)
  reverse = array.join('');
  n = Number.parseInt(reverse);
  return n;
}

Not the best, nor the simplest solution. But it does the job.

Cya. Drink water ???.

Previous

The above is the detailed content of Codewars - Descending Order. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:VS Code LLM = ?Next article:VS Code LLM = ?