"Typescript: Unraveling the Depths of Nested

Having trouble looping through nested arrays in a function that returns a statement.


selectInputFilter(enteredText, filter) {
    if (this.searchType === 3) {
        return (enteredText['actors'][0]['surname'].toLocaleLowerCase().indexOf(filter) !== -1);
    } 
}

Instead of manually specifying the [0] element of [actors], I would like to iterate through all elements of the array. However, I'm not sure how to implement a loop inside such a returning function. I attempted using forEach but encountered errors in my VSCode.

The complete pipe where nesting is needed is provided below. Unfortunately, it's not possible to include a loop within the last else statement. Additionally, the code seems a bit messy at this point, so any suggestions on simplifying it are appreciated.


export class InputFilterPipe implements PipeTransform{

    searchType: number;
    private subscription: Subscription;

    constructor(private movieService: MovieService) {
        this.movieService.getSearchType().subscribe(
            id => this.searchType = id
        );
    }

    transform(value: any[], filter: string): any[] {
        filter = filter ? filter.toLocaleLowerCase() : null;
        return filter ? value.filter(
            (arraySearched) =>
                this.selectInputFilter(arraySearched, filter))
            : value;
    }

    selectInputFilter(arraySearched, filter) {
        if (this.searchType === 3) {
            const values = [];
            for (let actor of arraySearched['actors']) {
                values.push(actor['surname'].toLocaleLowerCase().indexOf(filter) !== -1);
                for (let i = 0; i < values.length; i++ ) {
                    if (values[i] === true) {
                        return (arraySearched['actors'][i]['surname'].toLocaleLowerCase().indexOf(filter) !== -1);
                    }
                }
            }
        } else if (this.searchType === 2) {
            return (arraySearched['director'].toLocaleLowerCase().indexOf(filter) !== -1);
        } else if (this.searchType === 1) {
            return (arraySearched['title'].toLocaleLowerCase().indexOf(filter) !== -1);
        } else {
            return  (arraySearched['title'].toLocaleLowerCase().indexOf(filter) !== -1) ||
                    (arraySearched['director'].toLocaleLowerCase().indexOf(filter) !== -1) ||
                    (arraySearched['actors'][0]['surname'].toLocaleLowerCase().indexOf(filter) !== -1) ||
                    (arraySearched['actors'][1]['surname'].toLocaleLowerCase().indexOf(filter) !== -1) || 
                    (arraySearched['actors'][2]['surname'].toLocaleLowerCase().indexOf(filter) !== -1);
                    // (arraySearched['actors'][3]['surname'].toLocaleLowerCase().indexOf(filter) !== -1);
        }
    }

Answer №1

To create a generator function, you can follow this example:

function* filterInputSelection(enteredText, filter) {
  if (this.searchType === 3) {
    for (var actor of enteredText['actors']) {
      yield actor['surname'].toLocaleLowerCase().indexOf(filter) !== -1;
    }
  }
}

Then, you can use it in the following way:

for (var x of filterInputSelection(/*your args here*/)) {
  // x will iterate through each of the "returned" values
}

Alternatively, you can create and return an array of the desired values like so:

function filterInputSelection(enteredText, filter) {
  if (this.searchType === 3) {
    var values = [];
    for (var actor of enteredText['actors']) {
      values.push(actor['surname'].toLocaleLowerCase().indexOf(filter) !== -1);
    }
    return values;
  }
}

UPDATE:

If you choose to go with the second option, you can utilize Array.prototype.some as shown below:

} else {
  return (arraySearched['title'].toLocaleLowerCase().indexOf(filter) !== -1) ||
      (arraySearched['director'].toLocaleLowerCase().indexOf(filter) !== -1) ||
      (arraySearched['actors'].some((actor) => actor['surname'].toLocaleLowerCase().indexOf(filter) !== -1));
}

Another approach is by using a variable as follows:

} else {
  let returnValue = (arraySearched['title'].toLocaleLowerCase().indexOf(filter) !== -1) ||
      (arraySearched['director'].toLocaleLowerCase().indexOf(filter) !== -1);
  for (let actor of arraySearched['actors']) {
    if (returnValue) break; // stop looping once returnValue is true
    returnValue = returnValue || actor['surname'].toLocaleLowerCase().indexOf(filter) !== -1);
  }
  return returnValue;
}

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

What is the best way to access the attributes of a particular object following a triggered event?

I'm a bit unsure if my title makes sense, so allow me to explain. In a nutshell, I have 2 li elements within a ul list. What I aim for is that when one of these li elements is clicked, the text within that particular li is retrieved, and then an obje ...

The only React element that is rendered inside a for loop is the last one

I'm struggling with a function that is supposed to render an infinite number of strings as Comment components, but it only displays the last component. This is the function I'm working with: function displayComments(...comments) { for(let i ...

Is it possible to apply fog to a specific area in Three.js instead of being dependent on the distance from

Picture this: a vast THREE.PlaneGeometry representing the floor with a camera placed at an arbitrary spot within the scene. By manually adjusting the near and far values of the fog, I can effectively conceal the outer edges of the plane to create the illu ...

The use of p-message in Angular's PrimeNg library is not permitted

Hey there, I'm having a bit of trouble with the p-message Tag in Angular. I believe I've imported it correctly as shown below. import { MessageModule } from 'primeng/message'; imports: [ .... MessageModule, ... In the ...

The peculiar formatting issue with the jQuery datepicker that arises when adding more months

When adjusting the numberOfMonths parameter to a higher value such as 6, I noticed that the datepicker display appears unusual with the background extending further than expected. Take a look at my demonstration on jsfiddle: http://jsfiddle.net/zw3z2vjh/ ...

How come I'm able to access the form's control within setTimeout but not outside of it?

Having just started working with Angular, I came across a strange issue involving forms and setTimeout. When trying to access the form control of an input element inside setTimeout within the OnInit lifecycle hook, it works fine. However, when attempting t ...

Does nestjs support typescript version 3.x?

Currently embarking on a new project using Nestjs. I noticed in one of its sample projects, the version of Typescript being used is 2.8. However, the latest version of Typescript is now 3.2. Can anyone confirm if Nest.js supports version 3.x of Typescrip ...

Error encountered during Angular ahead-of-time (AOT) compilation: Internal state issue - Summaries cannot contain members in StaticSymbols

Our team is currently working on implementing ahead of time (AOT) compilation for our Angular 2 project, but we have encountered an error: Error: Internal state: StaticSymbols in summaries can't have members! {"filePath":"C:/Users/bhavy/Documents/p ...

Angular's Integration with PayPal for Shipping Costs

I am facing an issue with my e-commerce website where the receipt only displays the total payment of the items purchased. I have searched for an SDK that supports Angular or TypeScript PayPal integration, but could only find one for JavaScript which did ...

Utilizing HTML to call a function and fetching data from AngularJS

I've been struggling to retrieve the value after calling a function in my HTML file. Despite trying various methods after conducting research, I have not achieved success yet. Take a look at the code below: HTML: <div class="form-group"> & ...

Issues with dependencies in npx create react app

After initiating a new react project with npx create-react-app client, I have encountered an issue where the react-scripts command is not found, preventing me from running the start script. Is there a way to resolve this problem? Furthermore, when attempt ...

leveraging UI-Router for navigating based on app state and data

Is there a way to dynamically adjust Angular's ui-routing based on certain data conditions? For instance, let's say we need to create a subscription process where the user is informed of whether their subscription was successful or not. As the f ...

Javascript leaping across intervals

I'm currently working on creating a unique JavaScript slideshow with a customized pause interval for each slide. Let's say I have a slideshow with 3 slides and I want the pause intervals to be as follows: 30 seconds 8 sec 8 sec |---- ...

Displaying a random number triggers a snackbar notification in a ReactJS application

Currently, I am utilizing the notistack package to display a snackbar on the screen. However, when calling the Snack component with enqueuesnackbar, a random number is displayed along with the snackbar. I'm looking to eliminate this random number fro ...

Utilize Nuxt.js context within a Vue plugin

I have a situation where I'm working with Nuxt.js and have two plugins set up. In order to gain access to the VueI18n instance from lang.js within validate.js, I am in need of some guidance. Is there anyone familiar with how this can be accomplished? ...

What is the most efficient method for executing over 1,000 queries on MongoDB using nodejs?

I have a task to run around 1,000 queries on MongoDB in order to check for matches on a specific object property. I must confess that my code is quite amateurish, but I am open to any suggestions on how to improve its efficiency. The current version works ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

Having trouble converting data back to JSON format after using JSON.parse in an ejs file with node and express

I'm retrieving data from an external API on my server, then attempting to pass that data to an ejs file using JSON.stringify(data), and trying to read the data in the ejs file by parsing it with JSON.parse(data). However, I am encountering issues wher ...

The Dropbox picker is now launching in a new tab instead of a new window when using Chrome

I am encountering an issue with opening Dropbox picker in a new modal window. It works perfectly in all browsers except for Google Chrome. Is there anyone who can guide me on why it opens in a new tab in Chrome? Is there a parameter in options that I can ...

Transforming the typical click search into an instantaneous search experience with the power of Partial

I am working on a form that, when the user clicks a button, will display search results based on the entered searchString. @using (Html.BeginForm("Index", "Search")) { <div id="search" class="input-group"> @Html.TextBox("searchString", n ...