AngularJS: Selecting a trio of random items from a JSON dataset

Recently, I've been delving into AngularJS and I have a JSON file containing numerous objects that need to be displayed individually in separate partials. Out of the 100 objects in the JSON file, I'm looking to randomly select just three. How can I make this happen?

Here's a snippet from 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; // Planning 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;
  }

  });
}]);

At the moment, all 100 items are being selected...

Answer №1

If you want to retrieve a random element from your array, you can do so by using the following code:

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

By repeating this process three times, you can obtain three random elements from the array. To avoid repetition and keep your code concise, consider creating a function like the one below:

function getRandomElement(array) {

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

Answer №2

If the function is called three times in a row, it may return the same item multiple times. To avoid this, you can consider using the splice() method to remove the selected item from the original array.

function selectRandomItem(arr) {
    var randomIndex = Math.floor(Math.random() * arr.length);
    var selectedItem = arr.splice(randomIndex, 1);
    return selectedItem[0];
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to check the response headers in Express JS?

To view the incoming request headers, I typically use: req.headers. I am looking to see a comprehensive list of all headers that will be included in the response. Currently, res.headers returns undefined. I understand that I can set response headers usi ...

Converting JSON to object in C# on a Windows mobile device

I am currently working on deserializing JSON data received from a web server into an object. I have set up an HTTPWebRequest to fetch JSON formatted data from the server. public void SendHttpRequest(string url) { HttpWebRequest request = (HttpWebReque ...

Dealing with 404 Errors in AngularJS using ui-router's resolve feature

As a newcomer to AngularJS and ui-router, I am currently facing the challenge of handling 404 errors for resources not found. My goal is to display an error message without changing the URL in the address bar. Here is how I have configured my states: app ...

Retrieve the HTML code from a webpage on a different domain

Looking to extract HTML from another domain. Attempted solution: $.get("http://website1.com", function(data) { alert("Data Loaded: " + data); }); (not working) For example, as the owner of two websites: website1.com website2.com Now, the goal is to ret ...

Tips for minimizing the number of .js and .css files loaded when utilizing ng-view

Is there a way to optimize the inclusion of .js and .css files in index.html without including all of them like in the example below: <!DOCTYPE html> <html ng-app="MyApp"> <head> <base href="/"> <meta charset="utf-8"> & ...

Tips for showing menu only when a user scrolls on your WordPress site

I've been working on creating an effect where the menu stays hidden until the user starts scrolling. However, I can't seem to figure out why my code is not producing the desired effect. Here is the jQuery code snippet I am using: <script src= ...

Extracting props data from a component in React.js - a step-by-step guide

I am currently developing a react.js application with react-select. I have created a dropdown menu and when an item is clicked, I need to pass that item to a function that is connected to the redux store. How can I retrieve data from a component used in re ...

Encountering an obscure issue when using Discord.js v14 after attempting to cancel and resubmit a modal

I'm currently working on a Discord bot using modals in Discord.js v14. These modals appear after the user clicks a button, and an .awaitModalSubmit() collector is triggered to handle one modal submission interaction by applying certain logic. The .awa ...

What steps can I take to resolve the issue of encountering the error message "Module '@endb/sqlite' not found"?

Currently, I am facing a challenge while attempting to set up a database for my discord bot using node.js with sql/sqlite 3. I have installed the necessary dependencies such as 'endb', sql, and sqlite3 through npm install. However, upon completio ...

Fetch() is not executing in the expected sequence

I've been working on setting up an API to pull a word and save it to state. A function should then read that state and perform its intended task. However, my original coding approach caused it to run out of order. The third code snippet was able to fi ...

What could be the reason for my inability to reach function attributes?

Struggling with accessing properties in a function that involves callback functions. const example = ( callback: (...args: unknown[]) => unknown ): void => ({ name: callback.name // <- errors // ... }) Encountering issues in typescript d ...

When trying to display data using ng-repeat on a different user's profile page, I'm having trouble getting it to show up

My goal is to retrieve data when a user clicks on a username, redirecting them to their profile page. I'm attempting to achieve this using ng-click as shown below: <p style="font-size:11px; color: grey; " ng-click="seeProfile(gterest);changelocati ...

Eliminate viewed alerts by implementing a scrolling feature with the help of Jquery, Javascript, and PHP

My goal is to clear or remove notifications based on user scrolling. The idea is to clear the notification once the user has seen it, specifically in a pop-up window for notifications. I am relatively new to Javascript/jQuery and feeling a bit confused abo ...

Preventing the window from resizing while an AJAX query is in progress

I have a script in jQuery that serves as a search tool and also has the capability to resize an element to match the screen height minus 40 pixels whenever the window is resized. However, I am looking for a way to turn off the resizing feature when a searc ...

Gson in action - managing and accessing an ArrayList containing complex objects

I have a class named NameAndPosition that stores the name and position of users. I've created an ArrayList to hold objects of type NameAndPosition. ArrayList<NameAndPosition> LocSenders = new ArrayList<NameAndPosition>(); Using the Gson ...

The font displayed by Google looks black when viewed on iPhones, while it appears in its true color on all other

When I was optimizing my website for mobile devices, I noticed that the font size needed adjustment. Surprisingly, on Android phones, the text appeared in orange and normal, while on Safari and Chrome on iPhones, it didn't display correctly. I have i ...

Unable to send a post request via ajax in Laravel

I'm attempting to retrieve values from my table when clicked, here is the structure of my table: @foreach($inventory as $p) <?php $no++; $typesql = DB::table('product_variant_pos&apos ...

Error in Typescript occurrence when combining multiple optional types

This code snippet illustrates a common error: interface Block { id: string; } interface TitleBlock extends Block { data: { text: "hi", icon: "hi-icon" } } interface SubtitleBlock extends Block { data: { text: &qu ...

How to handle JSON serialization for keys with hyphens?

Is it possible to return JSON from my controller that was generated from an anonymous type and contains dashes in the key names? For example: public ActionResult GetJSONData() { var data = new { DataModifiedDate = myDate.ToShortDateString() }; re ...

Having trouble with Bing search API not functioning properly with AJAX?

Looking to incorporate Bing's search API using JavaScript. My goal is to allow the user to input a query and retrieve only images from Bing. I attempted to use Ajax for this task. When entering the URL directly in the browser, I successfully retriev ...