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

Unable to execute @angular/cli following installation

I recently set up the @angular/cli on my MacBook. The Node server version I am using is v6.9.5 and npm version 3.10.10. To install the @angular/cli, I executed the command below: sudo npm install -g @angular-cli However, whenever I try to run any ng co ...

Singleton constructor running repeatedly in NextJS 13 middleware

I'm encountering an issue with a simple singleton called Paths: export default class Paths { private static _instance: Paths; private constructor() { console.log('paths constructor'); } public static get Instance() { consol ...

Performing Cypress testing involves comparing the token stored in the localStorage with the one saved in the clipboard

I am currently working on a button function that copies the token stored in localStorage to the clipboard. I am trying to write code that will compare the token in localStorage with the one in the clipboard in order to verify if the copy was successful. H ...

The traditional function does not have access to a reference to this

For my web development project with Angular 9, I needed to add a typeahead feature using ng bootstrap typeahead. The code provided below worked perfectly: search = (text$: Observable<string>) => text$.pipe( debounceTime(150), disti ...

Messing with onBeforeUnload causes issues with the browsing history in Angular

After the user finishes entering data on a page, my goal is for them to return to the previous page (e.g. Main Page -> Input Page). If I redirect them when they click submit, it creates a circular history loop (Main Page -> Input Page -> Main Page). Theref ...

Is it possible to assign a property value to an object based on the type of another property?

In this illustrative example: enum Methods { X = 'X', Y = 'Y' } type MethodProperties = { [Methods.X]: { x: string } [Methods.Y]: { y: string } } type Approach = { [method in keyof Method ...

In Angular 12, encountering the error "Unable to bind to 'formGroup' as it is not a recognized property of 'form'" is not uncommon

Encountering a problem that seems to have been addressed previously. Error: Can't bind to 'formGroup' since it isn't a known property of 'form'. I followed the steps by importing ReactiveFormsModule and FormsModule in the req ...

Is it possible to upload an image-containing object to Mongodb with the help of Node.js?

I am struggling to upload an object containing an image to the mongodb database using Node.js. Angular File onSelectedFile(event){ this.edit_image = event.target.files[0]; } editProfile(e){ const user={ email:this.edit_email, img:this.edit_imag ...

What is causing the malfunction in this overloaded function signature?

Encountering an issue when attempting to declare an overloading function type with a full type signature in TypeScript. For example: // Full type signatures for functions type CreateElement = { (tag : 'a') : HTMLAnchorElement, (tag ...

The challenges of type verification in Redux reducer

I'm currently facing two specific challenges with Typescript and the Redux reducer. Reducer: const defaultState = { selectedLocation: { id: 0, name: 'No Location' }, allLocations: [{ id: 0, name: 'No Location' }], sele ...

Obtaining Data from an Array with Reactive Forms in Angular 4

Just starting out with Angular 4 and trying to figure out how to populate input fields with information based on the selection made in a dropdown. <select formControlName="selectCar" class="form-field"> <option value="">Choose a car&l ...

Error: The @use directive must come before any other rules in Angular

Error message: Issue: Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js): Error Details: HookWebpackError: Module build failed (from ./node_modules/sass-loader/dist/cjs.js) ...

Using typescript for Gnome shell extension development. Guidelines on importing .ts files

I'm currently working on a gnome shell extension using typescript, but I've encountered issues when trying to import .ts files. The Gnome shell documentation suggests configuring the tsconfig file as outlined in this Gnome typescript docs: { &q ...

What is the best approach to integrating payment solutions into a React Native application running on version 0

Seeking advice on integrating payment systems in React Native 0.70. Previously utilized react-native-credit-card-input and react-native-credit-card-input-plus with earlier versions, but they are now incompatible. ...

Yes, indeed - Entering the schema of a retrieved field from an Object schema

After deciding to upgrade from Yup version 0.29 to 1.2, I encountered some challenges with its types. Seeking assistance in finding the best solution for typing yup schemas. In version 0.29, the universal type Schema fit everywhere, but now it no longer d ...

Creating a typescript type for contextual dispatch by leveraging the values of another interface

I am seeking to define a specific type for my "reducer" function. The "reducer" function I have takes in 2 parameters: the current state and the data sent in the dispatch context (to be used by the reducer). const reducer = ( state: any, props: { ...

When downloading text using Angular, the file may not display new line characters correctly when opened in Notepad

When downloading text data as a .txt file in my Angular application using JavaScript code, I encountered an issue. Below is the code snippet: function download_text_as_file(data: string) { var element = document.createElement('a') eleme ...

Mistakes that occur while trying to expand a base class to implement CRUD functionality

Creating a base class in TypeScript for a node.js application to be extended by all entities/objects for CRUD operations is my current challenge. The base class implementation looks like this: export class Base { Model: any; constructor(modelName ...

Using Material UI Slider along with Typescript for handling onChange event with either a single number or an

Just diving into Typescript and encountered an issue with a Material UI Slider. I'm trying to update my age state variable, but running into a Typescript error due to the typing of age being number and onChange value being number | number[]. How can I ...

Issue with generating source map files using Webpack 4 and ts-loader

What mistake am I making here? When I execute webpack -d --config webpack.config.js, the map file is not generated along with bundle files. Here is my webpack.config.js: const path = require('path'); module.exports = { mode: "development" ...