Generate random entries from an object based on specific criteria and append them to a fresh object using Typescript

Experimenting with Ionic2 and Typescript has been my recent focus.

I have an object that contains various meals, calorie counts, and meal types (such as vegan).

This is how the object looks:

[
   {
      "id":14093,
      "name":"Proteinshake mit Wasser – ESN Designer Whey Protein",
      "description":"",
      "thumbnail":null,
      "image":null,
      "calories":[
         "200"
      ],
      "type":[
         "snack"
      ],
      "nutrition":[
         "pescetarier",
         "standart",
         "vegetarisch"
      ]
   },
   {
      "id":14088,
      "name":"Omelette mit Garnelen",
      "description":"",
      "thumbnail":null,
      "image":null,
      "calories":[
         "400"
      ],
      "type":[
         "fruehstueck",
         "gericht"
      ],
      "nutrition":[
         "pescetarier",
         "standart",
         "vegetarisch"
      ]
   }
]

Now I am looking to create a random meal plan.

I aim to include 3 random meals with 400 calories each and 2 Snacks with 200 calories each.

Is there a way to select meals randomly based on their calorie value?

Answer №1

Yes, it is absolutely achievable. Check out this simple demo on plunker to see how you can generate multiple meal plans effortlessly.

The code provided is quite clear and easy to understand:

import { Component } from "@angular/core";

@Component({
  templateUrl:"home.html"
})
export class HomePage {

  // Array containing all available meals
  private mealLists: Array<any> = [{...}, {...}, ...]; 

  // Array to store randomly generated meal plans
  private mealsPlan: Array<any> = [];

  constructor() { }

  // Generates a meal plan with specified *mealCount* and *calories*
  public getMealPlan(mealCount: number, calories: number) {

    // Reset data for new plan
    this.mealsPlan = [];

    for(let i=0; i<mealCount; i++) {
      // Retrieve meals with specified calorie count
      let selectedMeals = this.getMealsWithCertainCalories(calories);

      // Select a random meal from the list
      let randomMeal = this.getRandomMeal(selectedMeals);

      // Add the selected meal to the plan
      this.mealsPlan.push(randomMeal);
    }
  }

  // Filter meals based on calorie count
  private getMealsWithCertainCalories(calories: number) {
    return this.mealLists
      .filter(function(aMeal){
        if(parseInt(aMeal.calories[0]) == calories) {
          return true;
        } else {
          return false;
        }
      });
  }

  // Get a random meal index within the range of selected meals
  private getRandomMeal(selectedMeals) {
    let randomIndex = Math.floor((Math.random() * selectedMeals.length) );
    return selectedMeals[randomIndex];
  }

}

Note that the magic happens in the filter(...) and Math.random() methods.

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

shifting the angular directives to alternate the bootstrap class of hyperlinks

I have a collection of hyperlinks displayed on my webpage. <a href="#" class="list-group-item list-group-item-action active" routerLink='/route1' >Explore First Link</a> <a href="#" class="list-group-item list-group-item-action" r ...

It appears that the library (@ngx-translate/core) that contains TranslateModule may not be compatible with Angular Ivy, resulting in an error in the Angular application

Encountering an issue after upgrading my Angular app from version 15 to 16 and running npm start. The error message is related to compatibility with Angular Ivy, specifically mentioning @ngx-translate/core. Looking for a newer version of the library or adv ...

What is the reason behind the sudden red coloring of parentheses in Visual Studio Code while typing in TypeScript?

Previously, their color was white as showcased on https://code.visualstudio.com/docs/languages/typescript. ...

Tips for modifying date format in Angular 8

My datepicker for a date column is displaying the incorrect date format after submission. I am looking to change this format to the correct one. I am working with bsConfig bootstrap in Angular 8, but I am unsure of how to modify the date format. The back ...

Is it Possible for Angular Layout Components to Render Content Correctly even with Deeply Nested ng-container Elements?

Within my Angular application, I have designed a layout component featuring two columns using CSS. Within this setup, placeholders for the aside and main content are defined utilizing ng-content. The data for both the aside and main sections is fetched fr ...

Some font-awesome icons are not appearing on the screen

As a beginner in web design, I am experimenting with using font awesome icons in Angular 9 projects within list items. While some of the icons are displaying properly, others are not. You can see the issue in the attached image. To access the icons, I have ...

Adjust the size and color of text in Chart.js using Angular 5

Why does the font color in chartjs appear as light gray and not print when you want to do so from the page? I tried changing the font color of chartjs in the options attribute, but it didn't work. How can I change the font color in chartjs angular? ...

Sending selected IDs from the JSON data

In my project, there is a JSON file named "workers" which contains information about all the workers. I have created a select component to display the names of the workers like this: Currently, I am selecting some workers from the list and sending their n ...

Why include HTML in our webpack bundle?

Hello there, I am currently working on an angular 2 app using this starter pack as a base. I am trying to understand what our build process will entail. I have noticed that when running: npm run build:prod npm run server:prod The HTML content is incl ...

Steps to dynamically populate dropdown menus based on the selected options from other dropdown menus

I am working on a project that involves two dropdown menus. The options for the first dropdown menu are stored in a file called constant.ts. Depending on the selection made in the first dropdown, the options for the second dropdown will change accordingly. ...

What classification should be given to children when they consist solely of React components?

I'm encountering an issue where I need to access children's props in react using typescript. Every time I attempt to do so, I am faced with the following error message: Property 'props' does not exist on type 'string | number | boo ...

Displaying a component within an ngFor loop

During my iteration over an array of objects, I encountered a situation where I needed to specify a component to load within the object. For instance, one of the items in the loop looks like: { label: 'Patient\'s Weight', subtitle ...

Add items to QueryList in Angular

For my project, I am facing a challenge of combining two QueryLists. The issue is that I have multiple mat-options, with some being provided through ng-content outside the component and others inside the component itself. Essentially, I need to merge both ...

Unexpected silence from the Express web server

I am currently in the process of setting up my Angular application for Server Side Rendering using Angular Universal. Below is the JS file that has been generated by Angular Universal, with minor modifications made to the path and port: import 'zone ...

Encountering the "Unrecognized teardown 1" error when subscribing to an Observable in Typescript and Angular2

Having trouble with using an Observable in my Angular2.rc.4 Typescript app. Check out the plunker for it here: https://embed.plnkr.co/UjcdCmN6hSkdKt27ezyI/ The issue revolves around a service that contains this code: private messageSender : Observable< ...

Having trouble with Angular's ActivatedRoute and paramMap.get('id')?

Currently, I am attempting to retrieve information from my server using the object's ID. The ID can be found in the URL as well: http://xyz/detail/5ee8cb8398e9a44d0df65455 In order to achieve this, I have implemented the following code in xyz.compo ...

Encountering a style-loader error while trying to upgrade to Angular 15 using @angular-builders/custom-webpack

Check out my demo repository at the following link: https://github.com/OrShalmayev/style-loader-error After upgrading my Angular project from version 12 to 15, I encountered an issue with my angular.json file configuration: "architect": { &q ...

Automated Import Feature in Visual Studio Code

I'm currently transitioning from Webstorm to Visual Studio Code due to the poor performance of Webstorm. However, I'm facing issues with Visual Studio Code not being very efficient at detecting and importing the dependencies I need. I find mysel ...

What is the method for adjusting the time format?

Using the TIME data type, my data is currently displayed in the format hh:mm:ss (03:14:00). How can I change it to display in the format hh:mm (03:14)? The usual DATE type method does not seem to work: {{test.time | date: 'HH:mm'}} However, thi ...

Adding comments in TypeScript: A quick guide

Hey there, I'm new to TS and could use some help. Here is the code snippet I have: I want to comment out the logo but adding "//" and '/*' doesn't seem to work. This is what I tried: // <LogoComponent classes={{container: style.log ...