简体   繁体   中英

AngularJS: Getting three random elements from a JSON file

I have have been working with AngularJS. I have a JSON file of which each object needs to be displayed in a new partial. There are 100 objects in the JSON file, I need to randomly choose three. How do I achieve this?

the controller:

 myApp.controller('DetailsController', ['$scope', '$http','$routeParams' ,function($scope, $http, $routeParams) {
  $http.get('js/JOSCO.json').success(function(data) {
  $scope.questions = data; // Array of 100 objs
  console.log($scope.questions);
  $scope.whichItem = $routeParams.itemId; // I want to assign 3 random numbers to whichItem

 if($routeParams.itemId > 0){
    $scope.prevItem = Number($routeParams.itemId) - 1;
  }
  else{
    $scope.prevItem = $scope.questions.length - 1;
  }

  if($routeParams.itemId < $scope.questions.length-1){
    $scope.nextItem = Number($routeParams.itemId) + 1;
  }
  else{
    $scope.nextItem = 0;
  }

  });
}]);

Currently it is taking in all 100 items...

To access a random item in your array you can use.

$scope.randomItem = data[Math.floor(Math.random() * data.length)];

If you repeat it three times then you get the three random elements. Still you could create a function to make the code DRY.

function getRandomItem(items) {

  return items[Math.floor(Math.random() * items.length)];
}

The solution above could get the same item multiple times if it is called three times. You could use splice() to remove the item from the original array.

function getRandomItem(items) {
    var randomIndex = Math.floor(Math.random() * items.length);
    var item = items.splice(randomIndex, 1);
    return item[0];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM