0

I have some data in a JSON file and there are about 20 entries. What I would like to do is display 4 of those entries, at random, each time the page loads.

var data = [
  {'name': 'Bill'},
  {'name': 'Sally'},
  {'name': 'George'},
  {'name': 'Steve'},
  {'name': 'Jill'},
  {'name': 'Jeff'}
];

$.each(data, function(i) {
  var name = data[i].name;
  // Select 4 at random
  $('.results').append('<div>' + name + '</div>');
  
  if(i === 3) {  
    return false;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="results"></div>

I was able to make it so that it only displays 4 with my conditional statement, but how could I modify this so that it selects a random 4 rather than the first 4?

user13286
  • 3,027
  • 9
  • 45
  • 100
  • 3
    1. Shuffle an array https://stackoverflow.com/q/2450954/251311 2. Pick first 4 (using `Array.prototype.slice`) – zerkms Oct 17 '19 at 20:18
  • You really [don't need jQuery](https://i.stack.imgur.com/ssRUr.gif) just to randomly select some values from an array... – Patrick Roberts Oct 17 '19 at 20:20
  • A fairly easy way to do this is to shuffle the array elements, and select the first 4 from there. Here is a related topic: https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – Steve Pak Oct 17 '19 at 20:20
  • 1
    I suggest starting by selecting **one** random element from the array. – Code-Apprentice Oct 17 '19 at 20:21
  • Please find the below response - var data = [ {'name': 'Bill'}, {'name': 'Sally'}, {'name': 'George'}, {'name': 'Steve'}, {'name': 'Jill'}, {'name': 'Jeff'} ]; var totalData = data.length; $.each(data, function(i) { var random = Math.floor(Math.random() * Math.floor(totalData)); var name = data[random].name; $('.results').append('
    ' + name + '
    '); data.splice(random,1); totalData = totalData - 1; if(i === 3){ return false; } });
    – user3115056 Oct 17 '19 at 20:37
  • Thanks for the suggestions! – user13286 Oct 17 '19 at 21:57

1 Answers1

0

You can use this piece of cod.

    var rndList=[];
    var len=data.length
      while(rndList.length<4){
      var rnd=Math.floor((Math.random() * (len-1)) + 0);
       if(rndList.indexOf(rnd)==-1)
       {
        rndList.push(rnd)
       }
      }

    $.each(rndList, function(i) {
    var idx=rndList[i];
    var name = data[idx].name;

      $('.results').append('<div>' + name + '</div>');

    });
Abolfazl
  • 1,592
  • 11
  • 32