Filter an array of objects in Typescript by using another array of strings

I'm having trouble with my TypeScript filter function.

Here is an array of objects:

[
  {
    "id": 12345,
    "title": "Some title",
    "complexity": [
      {
        "slug": "1", // This is my search term
        "name": "easy"
      }, {
        "slug": "2", // This is my search term
        "name": "middle"
      },
{...}

Additionally, I have an array of strings containing the allowed complexities:

public allowedComplexityArray:Array<string> = ["1"];

My Objective: I want to display only the objects with the complexity "1".

However, my function is not working and I'm unsure why:

allowedMeals = meals.filter(meal => {
    return meal.complexity.every(complexityObj => that.allowedComplexityArray.indexOf(complexityObj.slug) > -1)
});

Answer №1

attempting:

const allowedOptions = data.filter(choice => {
    return choice.variety.findIndex(optionObj => 
        allowedVarietyArray.findIndex(o => o == optionObj.slug) > -1) > -1
});

Instead of using filter, I opted for findIndex in the return statement to avoid scanning through the entire array each time.

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

Where does tsc retrieve its definitions from when utilizing npm definitions?

After transitioning from using typings to just relying on npm, I noticed that the @types directory in node_modules is present, but there are no additional files required. Previously with typings, I always had to include the index.d.ts file within the typi ...

The Fusion of Apollo GraphQL Server and TypeScript: A Match Made

Lately, I've been immersed in a project that utilizes the node.js + express + typescript + Apollo server stack. During my research on Apollo client, I came across the TypeScript section, but surprisingly found little information regarding TypeScript f ...

How to declare multiple components in @ngModule using Angular 2

Currently, I'm working on a hefty project that combines Angular 2 with ASP.net MVC. I've got around 120 components declared within the @NgModule block like so: @NgModule({ imports: [CommonModule], declarations: [Component1, Component2, Comp ...

Having trouble reading the length property of undefined in Angular 7

Seeking to obtain a picture link of the object. The objects are stored in an array and the typescript method looks like this: getMealPicture(orderLineMeal: OrderLine): string { for (let meal of this.meals) { if (meal.id === orderLineMeal.mealId) ...

Tips on including a trash can symbol to rows in a bootstrap table using React

I am working on a table that contains various fields, and I want to add a trash icon to each row so that when it is clicked, the specific row is deleted. However, I am encountering an issue where the trash icon is not showing up on the row and I am unable ...

Tips for successfully sending a variable through setOnClickListener

Overview: The main layout, map_midvalley_g, contains 8 image buttons that can be clicked. Using a for loop on the data retrieved from the server, the color (green or red) of the image buttons is set. Clicking on any of the image buttons will trigger a popu ...

What is the most effective way to eliminate all values in an object key array except for one specific value?

Currently, I am developing an angular project and have encountered an object with the following structure: const obj = { fruits: ['apple', 'orange', 'None'], nation: ['usa'], city: ['New York', ' ...

Checking for a base class in Typescript

Is there a way to ensure type-checking for the handler class in the configuration object below? import { S01Handler } from "./handlers/start/S01Handler" const config: ConfigInterface = { states: { [StateEnum.S01]: { objec ...

Issue encountered with redux-toolkit's createAsyncThunk functionality

Here is how I implemented the deleteDirectories method in redux: export const deleteDirectories = createAsyncThunk( "directories/deleteDirectories", async (id, thunkAPI) => { try { const response = await axios.delete(`${url}direc ...

What to do when your Numpy array exceeds RAM capacity: Store to disk or use an out-of-core approach?

In my workflow, I have a process where I add data to an initial pandas Series object. This empty array could also be a NumPy array, or a simple list. in_memory_array = pd.Series([]) for df in list_of_pandas_dataframes: new = df.apply(lambda row: comp ...

Guide on altering an element's attribute in Angular 2

Is there a way in Angular to dynamically change the attribute of an HTML element? I want to create a button that can toggle the type attribute of an input from password to text. Initially, I thought about implementing it like this: Template: <input na ...

Mastering date selection in Angular 4 - Restricting days in the past and future

I am looking to restrict selection of future and past dates using an Angular 4 Date-Picker. I only want to enable the current date [today]. How can I accomplish this? Does anyone have any suggestions or ideas? This is the template I am currently using: ...

Dismiss the Angular Material menu using the controller

Hey there! I've come across a bit of an issue where I can't seem to figure out how to close an Angular Material menu from my controller. The button that opens the menu looks like this: <md-icon class="add-note__icon" [mdMenuTriggerFor]="pale ...

Obtaining a numpy array from the elements of a separate array (in Python)

Given an array like this [[ 430 780 1900 420][ 0 0 2272 1704]] I want to transform it into the following result: [[[ 430 780 1] [1900 420 1]] [[ 0 0 1] [2272 1704 1]]] To achieve this, I need to convert a 2D array into a 3D one, separate each s ...

Issue with Material UI grid not rendering properly in TypeScript environment

I've been trying to replicate a grid from material-ui using React and Typescript. You can see a live demo here. I modified the example to work with Typescript, so my demo.tsx file looks like this: Code goes here... If you check out the live demo, y ...

Supply additional parameters to the method decorator within an Angular component

Imagine a scenario where there are multiple methods requiring the addition of a confirmation dialog. In order to streamline this process, a custom decorator is created. @Component({...}) export class HeroComponent { constructor(private dialog: MatDialog ...

Implement a personalized Laravel Dusk selector with the attribute data-dusk

In the world of Laravel Dusk, the default selector hunts for the dusk="something" attribute in your HTML. If you want to dive deeper into this topic, check out this resource. However, when it comes to compatibility with Typescript for React/Vue, ...

Tips for utilizing SlowCheetah to modify array elements within a Json configuration file

Today is my first time working with SlowCheetah to transform a JSON configuration file. I am facing an issue where I cannot figure out how to transform an array of settings. For instance, if my original config file contains the following setting: { "Set ...

Is there any benefit to me verifying for Zone?

I have a custom function that allows me to execute another function within an Angular zone, regardless of whether it was called from outside of Angular. Check out my implementation: export class MyZones { public static maybe(zone: NgZone, callee: () ...

Stop extra properties from being added to the return type of a callback function in TypeScript

Imagine having an interface called Foo and a function named bar that accepts a callback returning a Foo. interface Foo { foo: string; } function bar(callback: () => Foo): Foo { return callback(); } Upon calling this function, if additional pr ...