Sort through the array of types and narrow down the selection based on the specified properties within each type

I am currently developing a project in Angular 9 using Typescript.

Within my project, I have both an array of strings and an array of a custom type.

My goal is to filter the array of custom types so that it only includes items whose property matches one of the strings in the string array. To illustrate, here is some code:

//Custom type declaration
export interface CustomType {
  id: string;
  name: string;
}

//Arrays initialization
customTypesArr: CustomType[] = [
    {id: "000", name: "name 1"},
    {id: "001", name: "name 2"},
    {id: "002", name: "name 3"}
];
customTypesNamesArr: string[] = ["name 3", "name 1"];

The desired outcome is to create a new array from customTypesArr that only contains items with a name property matching any string in customTypesNamesArr. The resulting array should look like this:

myNewCustomTypesArr: CustomType[] = [
    {id: "000", name: "name 1"},
    {id: "002", name: "name 3"}
];

I've attempted to achieve this filtering using the following code snippet, but I'm having trouble getting it right:

customTypesArr.filter(item =>
      customTypesNamesArr.forEach(name => {
        if (name == item.name) {
          return item;
        }
      })
    );

I am uncertain whether using forEach() is appropriate in this context...

If anyone could provide guidance or assistance on this matter, I would greatly appreciate it. Thank you.

Answer №1

  const result = customTypesArr.filter((element) => 
  {
   return customTypesNamesArr.includes(element.name);
  });

Answer №2

The task can be accomplished easily by utilizing the includes method available for arrays.

customTypesArr.filter(item => customTypesNamesArr.includes(item.name));

To simplify, apply a filter function where each item's name is checked against the array of permitted names using the includes method.

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

Setting up a winston logger in NestJS - A simple guide!

I am facing an issue with my nestjs app where I am trying to incorporate winston as a logger service. However, this implementation is causing my app to break and I am unsure how to resolve or revert this issue. I have attempted to uninstall the winston pa ...

What is the best way to transmit a two-dimensional array using ajax?

Here is the process I use to send data to the server: var points = []; var coords = polyline.geometry.getCoordinates(); for (var i = 0; i < coords.length; i++) { var x = (coords[i][0]).toFixed(4); var y = (coords[i][1]).toFixed(4); points[i ...

I noticed an excess of white space on the right side of my Angular website

Check out my website here. Everything seems to be functioning correctly, however, there is an issue with scrolling on mobile. It should only scroll up and down, not left and right! I have noticed a strange white space on the right side of my site when view ...

How to filter an array within an array using Angular

Currently, I am developing a project in Angular 9 and I have encountered a challenge regarding filtering an array based on another nested array within each object. To illustrate my issue, here is a sample of the array: const products = [ { name: &a ...

I require assistance with understanding how to utilize JSON effectively

Dealing with strings and arrays in jansson is proving to be quite challenging for me. unsigned char number[10]; // holds a hexadecimal array with up to 6 bytes After defining my array, I attempted to add it to a JSON object as follows: json_object_set_n ...

I am encountering a problem where I lose the values of a nested array of objects when trying to push it into another array

My goal is to format data for use with the amCharts library. The required structure should look like this: data = [{ name: "First", total: 190, children: [ { name: "A1", value: 100 }, { name: &q ...

Sending an array as an argument

I am facing an issue where only 2 values are being printed when passing an array as a parameter to another function: int i; int main() { int b[5] = {1, 2, 3, 4, 5}; printf("Main:\n"); for(i=0; i<sizeof(b)/sizeof(int); i++) { ...

What is the process of converting a default export to a named export?

Take a look at the following code snippet: const MyComponent = props => <div>Hello</div> export default React.memo(MyComponent) In this code, React.memo(MyComponent) is being exported as default. Is there a way to export it as a named expor ...

Are there more efficient alternatives to utilizing arrays and index-based functions for storing in-memory data in TypeScript?

Is there a more efficient method for storing and retrieving data besides relying on Array index-based calls? For instance: export interface EntityInterface { id: number; name: string; age: number; } export class ClassName { entities: Enti ...

React and TypeScript are mysteriously adding 'undefined' to a prop despite having defined defaultProps

Can you explain why the following code snippet triggers a warning about the possibility of name being undefined when strict mode is enabled, even though name is defined in defaultProps? type Props = { name?: string age: number } const Test = FC<P ...

Tips on preventing state sharing in Angular applications

Delving into the world of Angular has presented me with an intriguing issue. I've crafted a component dedicated to displaying a dialog, complete with its own template (HTML), CSS, and TypeScript files. Whenever a user clicks on an item within a list ...

Tips for implementing pagination in ag-Grid with Angular 2

Currently, I am working on developing a grid with pagination feature in Angular 2 using ag-grid. I have already attempted the code below in the HTML file: [gridOptions]="gridOptions" [columnDefs]="columnDefs" [showToolPan ...

Is there a circular dependency issue with ManyToMany relationships in Typescript TypeORM?

Below are the entities I have defined. The Student entity can subscribe to multiple Teachers, and vice versa - a Teacher can have many Students. import { PrimaryGeneratedColumn, Column, BeforeInsert, BeforeUpdate } from "typeorm" /* * Adhering to ...

When attempting to display database information, the word 'array' is unexpectedly printed instead

Every time I run my code, it displays the word "array" instead of the actual database information. Even when using print_r() or var_dump(), it still just dumps all the array details. When I use var_dump: array(1) { ["Team"]=> string(8) "Oakville" } ar ...

Why do ES6 classes fail to set properties when an overloaded function is called within the constructor of the parent class?

I encountered a puzzling scenario while coding that has left me perplexed. Here's the situation: I am extending a class from a library, which serves as the "Parent"-class. It allows its subclasses to override the init-method for custom initialization ...

The following 13 error occurred in the node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js file

Every time I try to use the serialize function in my application on Next, it throws errors. Error - node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js (40:0) @ parseCookieString Error - URI malformed I have attempted numerous soluti ...

Look up a string array using a specified user and provide the indexes of the matching string array elements

I am facing an issue with finding the indexes of phrases that contain a specific keyword in an array. var possibleValues=["contacts","delete","new contact","add","display"]; The user input can vary, it could be "contacts" or even "how to create a contac ...

Enhancing State Management with Multiple @Select Decorators in NGXS

I have a variety of @Selects within a component structured like this: @Select(ItemState.getMode) mode: Observable<Item>; @Select(QuestionState.SingleQuestion) question: Observable<Question>; @Select(ItemState.getItemNames) itemNames: Observabl ...

Getting the specific nested array of objects element using filter in Angular - demystified!

I've been attempting to filter the nested array of objects and showcase the details when the min_age_limit===18. The JSON data is as follows: "centers": [ { "center_id": 603425, "name" ...

Remove any repeated elements from the array and ensure that the element which occurs the most is placed at the beginning of the new array

Given an array "source" with values [2, 9, 9, 1, 6], we use the filter method to remove duplicate elements. The variable 'ans' stores the result. Now, how can we rearrange the elements in such a way that the highest repeated value (9) comes firs ...