0

I'm developing a recommendation widget that shows 4 random articles at the bottom of a blog post.

To do this, I need to append a random number between 0 through 5 to the end of the URL. This number can't repeat. Also, it only needs to perform the function until 4 articles are shown.

At the moment, the random numbers are generated, but they repeat. How do I write the jQuery code below so these numbers don't repeat?

HTML

<div class="recommended""></div>

jQuery

$(window).on("load", function() {

  var digits = [];

  for(var i = 0; i < 5; i++)
    digits.push(i);

  function timer() {

    var digit = digits.splice( Math.floor( Math.random() * digits.length ), 1 );
    var blogUrl = 'www.website.com/';
    var together = blogUrl + digit;

    $.get(together, function(data) {

      var recommendedArticles = $(data).find(".blog-title a");

      $(".recommended").append(recommendedArticles);

    });

  }

  var articleCount = $(".recommended a").length;
  for (; articleCount < 4; articleCount++) {
    timer();
  }  

});
Weebs
  • 155
  • 2
  • 10
  • Question is not clear. You say that you need 4 random articles. This is fixed. You need to apply the random selection on the list of articles (assuming its > 4). Am I correct? – Mulli Feb 20 '19 at 18:37
  • Possible duplicate of [Generating non-repeating random numbers in JS](https://stackoverflow.com/questions/18806210/generating-non-repeating-random-numbers-in-js) – imvain2 Feb 20 '19 at 18:37

2 Answers2

1

you can use a simple shuffle to get 4 random numbers from 0-5 range

function randomNumber() {
 const arr = [0,1,2,3,4,5];

 for( var i = 0 ;i < 6 ; ) {
   const a =  Math.floor( Math.random() * 6);
   const b =  Math.floor( Math.random() * 6);   
   if(a === b) { continue;}
   let temp = arr[a];
   arr[a] = arr[b];
   arr[b] = temp;
   i++;

 }
 return arr.slice(0,4);
}
ashish singh
  • 6,526
  • 2
  • 15
  • 35
0

Random Item from an Array

This expression is from the link above:

let digit = array[Math.floor(Math.random() * array.length)];

In the following demo the expression is modified to pick a random element from an array and reference an array length that's constant.


Demo

const digits = [0, 1, 2, 3, 4, 5];

/*
@Params: array - an array of integers
         limit - an integer that determines the minimum length of
                 returned array
@Return: A copy of the given array with a random order at the    
         minimum length of the given limit
*/
function mixDigits(array, limit) {
  let temp = [...array];
  let mixed = [];

  for (let i = 0; i < limit; i++) {
    let digit = temp[Math.floor(Math.random() * array.length)];
    let picked = temp.splice(digit, limit);
    mixed.push(picked);
  }

  while (mixed.flat().length < limit) {
    mixed.length = 0;
    return mixDigits(array, limit);
  }

  return mixed.flat();

}

console.log(mixDigits(digits, 4));
zer00ne
  • 41,936
  • 6
  • 41
  • 68