What is the best way to showcase a random index of an array in typescript?

Imagine a scenario where you have created a method that captures an array and selects a random position from it. The task at hand is to display one or more of these random positions on the screen. While you have successfully used the *ngFor directive to display all positions of the array, you are now faced with the challenge of figuring out how to specifically display these random positions.

listComics() {
    this.comicsService.getComics().subscribe(
      comicsList => {
        this.comics = comicsList.data.results;
        this.rareComics = comicsList.data.results[Math.floor(Math.random() * this.comics.length)]
        console.log(this.comics);
    });
  }

Here is the code snippet showcasing how the array is currently being displayed:


<div class="col-md-3" *ngFor="let comic of comics">
      <div class="col">
        <img [src]="comic.thumbnail.path + '/portrait_uncanny.' + comic.thumbnail.extension" id="img"
          (click)="onSelect(comic)">
      </div>
      <div class="col">
        <h5 class="title">{{comic.title}}</h5>
      </div>
    </div>

Answer №1

Check out this handy little function for your needs

function generateRandomComicList(comics){
    var radomLength = Math.floor(Math.random()*comics.length)
    var randomArray = []
    for(var i=0; i<=radomLength; i++ ){
        var randomIndex = Math.floor(Math.random()*comics.length)
        randomArray.push(comics[randomIndex])
        comics.splice(randomIndex, 1)
    }
    console.log(randomArray)
}

Or in ES6

generateRandomComicList(){
    let arr = [...this.comics]
    let randomLength = Math.floor(Math.random()*arr.length)
    let randomArray = []
    while(randomLength){
        let randomIndex = Math.floor(Math.random()*arr.length)
        randomArray.push(arr[randomIndex])
        arr.splice(randomIndex, 1)
        randomLength--
    }
    console.log(randomArray)
}

Hope this helps!

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

Setting angular variables by assigning form values

My current reactive form setup looks like this: this.editform = new FormGroup({ 'username' : new FormControl(null,[Validators.required]), 'password' : new FormControl(null,[Validators.required]), 'full_name' : ne ...

I'm encountering a Typescript error where I'm unable to assign a function to RefObject.current and it's indicating that the function is not callable

Does anyone know why assigning a function type to a ref.current type is causing me issues? useEffect(() => { savedHandler.current = handler; // ERROR HERE: }, [handler]); TS2741: Property 'current' is missing in type '(e: Chang ...

How to make an HTTP request only once after a certain period of time

I have an Angular 11 component with multiple dynamically included inputs in a table. After the user enters a currency value into any of these inputs, I make an API call to calculate the total. The issue is that I am calling the API multiple times, so I wa ...

Angular automatically protects routes by default

In the application I've created, there is a requirement for most routes to be protected and accessible only when logged in. Is it feasible to implement a default route guard while also specifying certain routes that should remain open? ...

What is the process of deploying Angular Server Side Rendering (SSR) build files to Azure Web App service using FileZilla FTP?

I'm currently working on Angular SSR and utilizing the Angular official sample project for testing purposes. Steps for building the Angular SSR project: Execute npm run build:ssr This will automatically generate the dist folder, which contains both ...

Is it possible to track each instance of change detection occurring at the component level?

Can we track each time Angular performs change detection on a component? For instance, if we have three components: foo, bar, and baz. During change detection, can we output the following using console.log: Run change detection on `foo`. Run change detec ...

Validating forms in Angular 5 with the help of ngx-bootstrap

I am currently delving into Ari Lerner's ng-book about Angular 5. My setup includes ngx-bootstrap and Bootstrap 4. However, I am facing an issue with form validation that doesn't align with Mr. Lerner's implementation. I'm unsure whethe ...

Steps for passing the :id parameter to an Angular 2 service using routes

Currently, I am trying to find a way to pass a Mac ID into a service using routes in order to filter data efficiently. In my app.html file, there is a dropdown menu where I manually input a list of Mac addresses. Through Angular activated routes, I am atte ...

The resend email feature isn't functioning properly on the production environment with next js, however, it works seamlessly in the development environment

import { EmailTemplate } from "@/components/email-template"; import { Resend } from "resend"; const resend = new Resend("myApiKey"); // this works only in dev // const resend = new Resend(process.env.NEXT_PUBLIC_RESEND_API_KE ...

What is the best way to retain multiple values passed through Output() and EventEmitter() in Angular?

In my Angular application, I have implemented custom outputs to transmit user-selected values between components. Currently, the functionality allows for the selected value from checkbox items to be sent to a sub-component, where it is displayed in the con ...

Using Angular2 in conjunction with the simpleheat plugin

I've been attempting to integrate the NPM plugin Simpleheat () into my Angular2 app, but unfortunately, the heatmap is not rendering even though everything appears to be set up correctly. You can find the full repository with the issue here: https:// ...

Set a timeout for a single asynchronous request

Is there a way to implement a setTimeout for only one asynchronous call? I need to set a timeout before calling the GetData function from the dataservice, but it should be specific to only one asynchronous call. Any suggestions? Thank you. #html code < ...

Setup a Single Page Application on Google Cloud Storage with Load Balancer and Content Delivery Network

I am currently exploring how to deploy an Angular or React web application on Google Cloud using GCS, Load Balancer, and CDN. I've configured the LB and the GCS using the urlRewrite feature. However, due to the LB's limitation on full URL rewrit ...

Combining array elements into functions with RxJS observables

I am facing a scenario where I have an array of values that need to be processed sequentially using observables in RxJS. Is there a more optimized way to achieve this instead of using nested subscriptions? let num = 0; let myObs = new Observable(obs ...

Is the window.location.href of a component not inside a router-outlet updated after a router redirect through a guard?

The navigation component I have is positioned outside of the router. It utilizes a reusable icon component that depends on absolute URLs to point to SVG icons, retrieved through a getter within the component: public get absUrl(): string { return windo ...

How to dynamically track changes in Angular2 form fields: Using the formbuilder to

Currently, I'm working with ionic2 and angular2. I have a form constructed using formbuilder but I am looking to monitor any new changes made to a specific input. ionViewDidLoad() { this.purchaseDataForm = this.formBuilder.group({ kms: ['& ...

Attempting to integrate Bootstrap 5 accordion into Angular 17 using ngFor has posed a challenge for me

<div class="accordion w-50 mx-auto" id="accordionExample"> <div *ngFor="let note of notes; index as i;"> <div class="accordion-item"> <h2 class="accordion-header" id="headi ...

Issue with populating virtual IDs in NestJS mongoose schema containing an array of schemas

In the schema provided below, I have defined the structure for Map, Marker, and Desk: export type MapDocument = Map & Document @Schema({ timestamps: true, versionKey: false, id: true }) export class Map { constructor(partial?: Partial< ...

Exploring the Power of Dynamic XML in Your Angular 4/5 Application

If example.com is an active angular 4 application with existing routes such as /product and /category, how could I create a route like /products.XML or /category.xml to display dynamic XML content for each. ...

What is the method to ensure that the option group is selectable?

Is there a way to enable the selection of an option group? <select> <optgroup value="0" label="Parent Tag"> <option value="1">Child Tag</option> <option value="2">Child Tag</option> </optgroup> ...