Is it possible to retrieve a randomized set of the top 10% results from an Angular Material data source?

Sorry for the roughness of the code. It's a work in progress. While I believe it's almost working, I'm struggling to complete it. My goal is to display 10% of the results from an HTTP POST request in a material table. Any tips would be appreciated.

RandomSample() {

    const headers = { 'content-type': 'application/json' };

    var userId, roleId, eventTypeIds: any[];
    if (this.selectedUser == undefined) {
      userId = 0;
    }
    else {
      userId = this.selectedUser.id;
    }
    if (this.selectedEventTypes == undefined) {
      eventTypeIds = [-1];
    }
    else {
      eventTypeIds = this.selectedEventTypes.map(selectedEventTypes => selectedEventTypes.id);
    }

    var SearchStart, SearchEnd
    if (this.searchStartDate == undefined) {

      var ssd = new Date();
      ssd.setDate(ssd.getDate() - 14);
      SearchStart = ssd;
    }
    else {
      SearchStart = this.searchStartDate;
    }

    if (this.searchEndDate == undefined) {

      SearchEnd = new Date();
    }

    else {
      SearchEnd = this.searchEndDate;
    }

    var body = JSON.stringify({ UserId: userId, EventTypeIds: eventTypeIds, SearchStartDate: SearchStart, SearchEndDate: SearchEnd });
    console.log(body);
    this.http.post(environment.BASE_URL + 'useractivity/getloginsoverfourteendays', body, { 'headers': headers }).subscribe((selectedUser: any) => {
      var random = Math.floor(Math.random() * selectedUser.length);
      this.dataSource = new MatTableDataSource(selectedUser[random]);
      console.log();
    }, (error: any) => {
      console.error(error);
    })

  }

Answer №1

One way to extract a portion of items from this.selectedUser[] is by using the slice(startIndex, endIndex) method based on the length of this.selectedUser. This approach will specifically select 20% of the initial items.

 selectedUser = Array.from(Array(100).keys()) // [1,2,3,...100]

 function httpCall() {
    const percent = 20;
    const strartIndex = 0;
    const endIndex = (percent * this.selectedUser.length / 100)
    const dataSource = this.selectedUser.slice(strartIndex,Math.floor(endIndex))
    console.log(dataSource)
  }
  
  this.httpCall()

If you prefer to randomly select the same number of items based on a given percentage, we can implement a helper function that picks items randomly and ensures no duplicates in return.

 selectedUser = Array.from(Array(100).keys()) // [1,2,3,...100]

 function httpCall() {
    const percent = 20;
    const dataSource = this.selectRandomItems(percent, this.selectedUser);
    console.log(dataSource);
  }

 function selectRandomItems(percent, selectedUser) {
    const totalCount = Math.floor((percent * this.selectedUser.length) / 100);
    let returnArr = [];
    while (returnArr.length < totalCount) {
      let item = selectedUser[Math.floor(Math.random() * selectedUser.length)];
      returnArr.push(item);
      returnArr = [...new Set(returnArr)];
    }
    return returnArr;
  }
  
  this.httpCall()

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

What could be causing a blank page to appear after being redirected? (Using NextJS 13 API Route)

After struggling with this issue for 2 days, I'm throwing in the towel and reaching out to the community for assistance. I've been tasked with setting up a basic login system for a new project using NextJS v13. However, it seems like a lot has c ...

Encountering unanticipated breakpoints in compiled .Next files while using Visual Studio Code

As a newcomer to NextJS, I have encountered an issue that is disrupting my workflow. I followed the instructions in https://nextjs.org/docs/advanced-features/debugging#using-the-debugger-in-visual-studio-code to set up my launch.json file. Although I am ...

Is dynamic routing in Angular 8 only functional when utilizing RouterLink?

While working on dynamic routing in Angular, I ran into a strange issue. Dynamic routes only seem to be functional when accessed through a RouterLink, but the app crashes whenever I try to directly enter the URL in the browser. (The console error message ...

Combining Repetitive Elements in an Array

Trying to combine an array of products with the same order_id while also including all objects from a second products array. Below are some sample orders: const orders = [ { "order_details": { }, "order_id": "1", ...

"Enhance user experience with Angular Material: Popup Windows that preserve functionality in the original window while staying vibrant and accessible

Exploring Angular Material Dialog and other Popup Window Components for a project. Making progress but facing some challenges. Here are the requirements: a) The original screen should not be grayed out, b) Users should be able to interact with the windo ...

A versatile tool for creating customizable components on the fly

I am looking to create a function within my service that generates dynamic components into a ViewChild reference... I attempted to do this by: public GenerateDynamicComponent(ComponentName: string, viewContainerRef: ViewContainerRef, data?: any) { sw ...

In Javascript, what significance does the symbol ":" hold?

While exploring the Ionic framework, I came across the following code snippet: import { AlertController } from 'ionic-angular'; export class MyPage { constructor(public alertCtrl: AlertController) { } I'm curious about the significanc ...

Sending a message through Discord.JS to a designated channel

Recently diving into Discord.JS, I am struggling to understand how to make my bot send a message to the General Chat when a new user joins. Many examples I've come across suggest using the following code: const channel = client.channels.cache.find(ch ...

What is the best method for managing an event loop during nested or recursive calculations?

When it comes to breaking a computation and releasing using setTimeout(), most examples seen involve having a shallow call stack. But what about scenarios where the computation is deeply nested or mutually-recursive, like in a tree search, with plenty of c ...

Creating a TypeScript class without using the prototype method

Recently delving into TypeScript and encountering a perplexing issue for which I can't seem to locate a satisfactory explanation... Let's suppose I have a function: function test() { function localAccessMethod() { console.log(' ...

Invoking a parent component's function using jQuery summernote

I'm having trouble calling a function from outside of a custom button component that I am adding to the ngx-summernote toolbar. The code I currently have is causing compilation errors. I've tried various methods, but they all result in an error s ...

Solutions for Utilizing Generic Mixins in Typescript

As a newcomer to Typescript, I have encountered an issue with mixins and generics. The problem became apparent when working on the following example: (Edit: I have incorporated Titian's answer into approach 2 and included setValue() to better showcas ...

What could be causing ConnectedProps to incorrectly infer the type?

My redux state is rooted and defined as: interface RootState { users: User[] } When working with components, I want to utilize ConnectedProps to generate the props type automatically from my state mapping and dispatch mapping: const mapState = (state: ...

Typescript error: the argument passed as type a cannot be assigned to the parameter of type b

In my programming interface, I have defined shapes as follows: type Shape = | Triangle | Rectangle; interface Triangle {...} interface Rectangle {...} function operateFunc(func: (shape: Shape) => void) {...} function testFunction() { const rectFun ...

When a webpage reload triggers a 404 error, my website's iframe with the source "videoUrl | sanitize" will display

I am attempting to retrieve a videoUrl from a database and set it to the iframe [attr.src] in order to display a YouTube video. It is imperative that the data originates from the database, as there are limitations preventing us from directly uploading and ...

Encountering an issue while constructing a JSON path in SQL using values from a column

When running the query below, I encountered an error: The second argument of "JSON_VALUE or JSON_QUERY" must be a string literal. SELECT JSON_QUERY(sr.Options, CONCAT('$[', sr.OptionId,']') FROM Survey as sr The 'Options' ...

Exploring the Concepts of Union and Intersection Types in Typescript

I am trying to wrap my head around Union and Intersection types in TypeScript, and I've come across a case that's puzzling me. You can check it out on this Playground Link interface A { a: number; } interface B{ b: boolean; } type Un ...

Once the data being interpolated undergoes a change, implement a setTimeout function in Angular 7

To hide the element with a specific value when displayed I attempted to monitor the incoming message (which changes from an old value to a new one) and added a timeout to the new message. However, there is a delay between the message arriving and appearin ...

Having trouble with npm install on an Angular project? It seems to be failing with an ECONNREFUSED error while trying to

I am facing an issue while trying to clone one of my Angular projects. To make it work, I need to run npm install, which used to work fine in the past. However, recently I encountered the following error: npm install npm ERR! code ECONNREFUSED npm ERR! ...

What is the method for converting a JSON string into an [object][object] format using Angular 6?

Is there a way to transform the data shown below into the [[object][object]] structure using Angular 6? resultArray = [{Q_id: "5bbee2fbbb34b98be0464c73", opt_id: 111},{Q_id: "5bbee2fbbb34b98be0464c73", opt_id: 113}] ...