Combining comparable lines of code in the following code for filtering arrays

I find myself using the same array filter function repeatedly within my if else conditions, with only the properties changing in each case. Is there a way to consolidate them or is it fine as it is currently structured below?


private _filter(value: string, filterIndex, type: string): string[] {
    let filterArray = [];
    const filterValue = value.toLowerCase();
    if (filterIndex == 0) {  // Index for Type
      if (type === 'Dsc') {
        this.assetTypeData.filter((option) => option.assetTypeDsc.toLowerCase().includes(filterValue)).forEach(element => {
          filterArray.push(element.assetTypeDsc)
        });
      } else {
        this.assetTypeData.filter((option) => option.assetTypeCde.toLowerCase().includes(filterValue)).forEach(element => {
          filterArray.push(element.assetTypeCde)
     });
   }
} else if (filterIndex == 1) { // Index for Make

      if (type === 'Dsc') {
        this.assetMakeData.filter((option) => option.assetMakeDsc.toLowerCase().includes(filterValue)).forEach(element => {
          filterArray.push(element.assetMakeDsc)
        });
      } else {
        this.assetMakeData.filter((option) => option.assetMakeCde.toLowerCase().includes(filterValue)).forEach(element => {
          filterArray.push(element.assetMakeCde)
     });
}

Answer №1

Attempted to categorize all relevant elements for better organization

private _filter(value: string, filterIndex, type: string): string[] {
    const lowercaseValue = value.toLowerCase();
    return (filterIndex == 0 ? this.assetTypeData : this.assetMakeData)
       .map(option => option[(filterIndex == 0 ? 'assetType': 'assetMake') + type])
       .filter(assetValue => assetValue.toLowerCase().includes(lowercaseValue));
}

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

Angular 7 triggers the event on only the initial click

I am facing an unusual problem while trying to implement a file upload feature in my Angular application. The issue is that the event only gets triggered on the first click. template <input multiple type="file" (change)="onFi ...

Arrange the object's key-value pairs in ng-repeat by their values

I'm completely new to AngularJS and I am working with an API that returns key-value pairs related to different sports. $scope.sports = { 1: "Soccer", 2: "Tennis", 3: "Basketball" ... }; My challenge is sorting these items by sport name: <ul> ...

The error encountered was: "Value is not in Array format"

Currently, I am facing a challenge with Google Maps integration. When I manually input the latitude and longitude values, everything works perfectly: var triangleCoordsLS12 = [ {lng: -1.558585, lat: 53.796545}, {lng: -1.558585, lat: 53. ...

create a fresh variable instead of appending it to the current object

I'm encountering an issue where a new array is supposed to be added on callback using props, but instead an empty variable is being added. Here's the code snippet: const [data, setData] = useState({ title: "", serviceId: "", serviceNa ...

What are the steps to manipulate third party API data with the Node.js 'Request' module, prior to transmitting it to the frontend?

Being a newcomer to NodeJs, I took to Google for assistance but came up empty. My challenge lies in editing the json data retrieved from an API link and sending it to frontend AngularJS as is. app.get('/getCustomers', bodyParser.urlencoded({exte ...

Error: Attempting to assign a value to 'onclick' property of null object [Chrome Extension]

window.onload = function() { document.getElementById('item_save').onclick = function() { var item_name = document.getElementById('item_name').value; var item_size = document.getElementById('item_size').value; v ...

Ways to access a JavaScript object beyond the function scope

Using the code below, I am able to retrieve JSON data when an element is clicked. This data is then used to create a table, fill the cells with images, and append the table to a specific div. function LoadImagesByCategory() { $.getJSON("/Service/GetJs ...

I aim to showcase particular cookies within an input field using jQuery

I am seeking a way to create a responsive page that showcases cookies. My goal is to have the output of a function automatically appear in the input value upon loading the page, instead of requiring a click event. Here is the code snippet I have been worki ...

What is the best approach for dynamically accessing or rendering Children within an Angular Component?

I am facing an issue with reusing a component called wrapper with different child components. I found some helpful resources such as this SO question and this article. However, these only address cases where the child component is known in advance. In my s ...

Disabling past dates on Kendo datepicker in Angular 2: A step-by-step guide

<kendo-datepicker formControlName="departureValue" [format]="'MMM-dd-yyyy'" (click)="ChangeReturnDate()"></kendo-datepicker> Is there a way to accomplish this in my code? ...

No recommended imports provided for React Testing Library within the VS Code environment

I am currently in the process of setting up a Next JS project with Typescript integration and utilizing React Testing Library. Unfortunately, I'm facing an issue with getting the recommended imports to work properly within my VS Code environment. To i ...

What methods can Ajax utilize to make asynchronous requests and receive synchronous responses?

While using jQuery ajax to send a request to a web service, I came across an interesting bug: var AjaxResult; login = function () { AjaxResult = ""; $.ajax({ type: "POST", url: KnutBase.getServiceUrl() + "ServiceInterface/HmsPlanne ...

What could be causing this issue of the Angular Material table not displaying properly?

I have been developing a Contacts application using Angular 9 and Angular Material. The goal is to display contact information and an image for each contact in a table row within the list component. Within my app.module.ts, I have imported various modules ...

How can we avoid the page from refreshing when clicking on a link in React js? Currently, the entire page refreshes when the link is clicked

I need a link that, when clicked, will display the data for a specific invoice number without refreshing the page. [code] ...

Converting a string array to an array object in JavaScript: A step-by-step guide

My task involves extracting an array from a string and manipulating its objects. var arrayString = "[{'name': 'Ruwaida Abdo'}, {'name': 'Najlaa Saadi'}]"; This scenario arises when working with a JSON file where ce ...

Aggregate together the fields that have a value of true to calculate their sum

Model.aggregate([ { '$group': { '_id': '$id', 'name': { '$first': '$name' }, 'tof': { $sum: { $eq:["$tof",true] } }, } } ]) .... // rest of the code. ...

Creating a menu with items and listeners from a kmllayer - a step-by-step guide

Currently, I am working with a map that includes a kmllayer. This layer has been added using the following code: ctaLayer = new google.maps.KmlLayer('http://www.npd.no/engelsk/cwi/pbl/en/aFactGlobe/disc/ActivityStatus_Producing_labels.kml'); ...

Generate a JavaScript File/Blob from an image's URI

Can I generate a File or Blob object from an image URI? I am utilizing the Cordova Image Picker plugin in my mobile application to retrieve photo URIs like this: "file:///data/user/0/..../image.jpg" However, I am struggling to create a File or Blob objec ...

Can Vuex mapActions be utilized within a module that is exported?

Is it possible to utilize Vuex mapActions from an external module imported into a component? I am working on standardizing a set of functions in a vue.js web application. My goal is to import these functions into each component and pass necessary values f ...

Missing Values in jQuery Variable

I'm having trouble with adding a link after a block of text. Although the links render fine, the href tag seems to disappear. var eventstuff = data.text; var eventElement = $("<div class='well well-sm eventsWells'>"); var deleteButton ...