Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript sort array using day of month

I want to change the order of a string based on what day of the month it is.

For example, say the word is "PIZZAS", on the 1st of May it will be "ZZSIPA", and on the 2nd of May it will be "APIZZS" etc…

The code I run works for Math.random(), however when I assign it the value of the day of the month, it does not change.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    const dayOfMonth = new Date().getDate();

function shuffle(s) {
    
  var arr = s.split(''); 

for (let i = arr.length -1; i > 0; i--) {
  let j = Math.floor(dayOfMonth * i)
  let k = arr[i]
  arr[i] = arr[j]
  arr[j] = k
}
    
  s = arr.join(''); 
  return s; // Return shuffled string
    
}
var s = shuffle("PIZZAS");

>Solution :

Math.random() returns a float between 0 and 1, new Date().getDate() returns an integer between 1 and 31, so if you want to get the same behavior you should divide the day of month by 31.

But note that this pseudo-random number generator is not very good and you’d probably get less predictable results with something from question about seeding JS random number generator.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading