Filtering without the includes() Method

I have two Objects that are structured as follows:

export const recipes: Recipe[] = [
  new Recipe( id: "Green", scenario: ["1", "2"]),
  new Recipe( id: "Blue", scenario: ["1", "2","2"])
];
export const scenarios: Scenario[] = [
  new Scenario( id: "1", ...),
  new Scenario( id: "2", ...)
];

Within my Recipe model, I have implemented a function to fetch Scenarios based on their id: string:

  getScenario(): Scenario[] {
    return scenarios.filter(scenario => this.scenario.includes(scenario.id));
  }

This function filters Scenarios based on matching the id: string.

The issue arises when a property scenario: string[] contains the same id: string multiple times. In such cases, it returns an array with ["1", "2"] instead of ["1", "2","2"], which is what I need.

Answer №1

Filtering scenarios implies that each scenario (1, 2, 3, etc.) will be accessed once. To achieve the opposite order, you should loop through this.scenario.

Since using filter wouldn't provide the stored scenarios in scenarios, your getScenario() function needs to be:

getScenario(): Scenario[] {
    return this.scenario.map(scenarioValue => scenarios.find(s => s.id == scenarioValue));
}

Answer №2

It's recommended to utilize the map function here.

getScenario(): Scenario[] {
  return this.scenario.map(scn => scenarios.find(s => s.id === scn));
}

This approach will iterate through all the elements in recipe.scenario and transform them into instances of Scenario.

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

"Encountering an issue with AngularJS where the selected ng-model value is

I'm utilizing plain options for the select tag because I only need to display a few options when they meet a certain condition. In order to perform other operations, I require the value of the selected dropdown in the controller. However, the issue is ...

Accessing an unregistered member's length property in JavaScript array

I stumbled upon this unique code snippet that effectively maintains both forward and reverse references within an array: var arr = []; arr[arr['A'] = 0] = 'A'; arr[arr['B'] = 1] = 'B'; // When running on a node int ...

JavaScript example: Defining a variable using bitwise OR operator for encoding purposes

Today I came across some JavaScript code that involves bitwise operations, but my knowledge on the topic is limited. Despite searching online for explanations, I'm still unable to grasp the concept. Can someone provide insight into the following code ...

I'm a beginner with Angularjs and I attempted to populate multiple JSON values, but unfortunately, it didn't work as expected

<div ng-controller="studentController" ng-repeat = "student in students | unique = 'RollNo' " > <table class="profile-info"> <tr> <th>Enrollment Number</th> <td> ...

Unable to save cookies using AngularJs

Currently, I am immersed in a small project utilizing AngularJs. The main objective of this project is to save a user's username and password within browser cookies. Here is my snippet from app.js where you can observe ngCookies being injected as a d ...

What steps can I take to ensure that the content remains intact even after the page is

Hey there, I hope you're having a great start to the New Year! Recently, I've been working on creating a calculator using HTML, CSS, and JavaScript. One thing that's been puzzling me is how to make sure that the content in the input field do ...

Refreshed page causing hide/show div to reset

Hello there, I'm currently working on a web application and I need to implement some JavaScript code. The application consists of three sections, each with its own title and button. When the button is clicked, a hidden div tag is displayed. Clicking t ...

What could be causing the function to not execute before the rest of the code in the React App?

My lack of expertise may be the reason, but I'm unsure how to address this issue: Here's what I have: A button labeled "Check numbers" <Button fullWidth variant="contained" onClick={this.checkOptOut ...

Displaying an element outside with reduced opacity using fabric js and controls placed above overlay

The property controlsAboveOverlay in Fabric.js is a boolean that, when set to true, will display the controls (borders, corners, etc.) of an object above the overlay image. The overlay image is an image that can be placed on top of the canvas. Currently, ...

Looking for help combining HTML5 Canvas and JavaScript to showcase images. Can anyone lend a hand?

I am currently in the process of developing an Android game using HTML5 and Javascript. I have managed to make some progress, but I have encountered a problem that has left me puzzled. Initially, my JS file and Html file were functioning well together for ...

implementing an event listener in vanilla JavaScript with TypeScript

Can anyone help me figure out how to correctly type my event listener in TypeScript + Vanilla JS so that it has access to target.value? I tried using MouseEvent and HTMLButtonElement, but I haven't been successful. const Database = { createDataKeys ...

After clicking, revert back to the starting position

Hey there, I have a question about manipulating elements in the DOM. Here's the scenario: when I click a button, a div is displayed. After 2 seconds, this div is replaced by another one which has a function attached to it that removes the div again. ...

Incorporating a text box underneath the model image

My application currently utilizes a grid gallery that perfectly fits my needs. However, there are two specific changes I need to make in order for it to be complete for my purpose. Unfortunately, I am struggling to figure out how to implement these changes ...

Separating express routes into individual files

After trying multiple solutions from Stack Overflow and various patterns for organizing routes in Node.js, I still can't seem to get it right. The endpoint either throws errors or returns a 404. Despite following suggestions from different sources lik ...

TypeORM Error: Trying to access property 'findOne' of an undefined object

I've been working on implementing TypeORM with Typescript, and I have encountered an issue while trying to create a service that extends the TypeORM repository: export class UserService extends Repository<User> { // ... other service methods ...

What is the best way to add a new project and make updates to an existing project within an array?

Looking to add a new project and update existing projects within an array. Here's my plan in pseudo-JSON format. How can I update Project A in MongoDB? { _id : ..., userName: milad , projets : [ { .. projectId, pName, location .... A }, ...

What is the best method for importing Bootstrap into SvelteKit?

I am currently working on a SvelteKit website. I have integrated Bootstrap 5 into my project by adding it to the app.html file provided by the SvelteKit Skeleton starter project: <!-- Bootstrap styles and javascript --> <link rel="stylesheet ...

Tips for encoding ParsedUrlQuery into a URL-friendly format

Switching from vanilla React to NextJS has brought about some changes for me. In the past, I used to access my URL query parameters (the segment after the ? in the URL) using the useSearchParams hook provided by react-router, which returned a URLSearchPara ...

Rendering a Nativescript component once the page has been fully loaded

I'm currently working on integrating the WikitudeArchitectView into my TypeScript code. I've successfully registered the element in the main.ts TypeScript file: var architectView = require("nativescript-wikitudearchitectview"); registerElement ...

Unable to load the JSON texture file

I recently exported a 3D model to JS from Blender, but I'm encountering an issue with the texture not showing up properly. Even when I remove the texture file, the browser generates an error saying that 'map.png' cannot be found. This indica ...