Using TypeScript to efficiently filter an Array by converting all values to lowercase

I have a custom array in TypeScript that needs to be filtered based on the city and job, with case-insensitivity as a requirement.

 array = [{ name: "Hardik", city: null, job: null },
  { name: "John", city: "Ahmedabad", job: "IT" },
  { name: "Margie", city: "Mumbai", job: "CA" },
  { name: "Creature", city: "Banglore", job: null },
  { name: "Smooth", city: null, job: null }];

In order to achieve this, I apply a filter while converting all values to lowercase to prevent errors when dealing with null columns.

this.filter = this.array.filter(i =>
  i.job.toLowerCase().indexOf('ca') != -1 ||
  i.city.toLowerCase().indexOf('ahmedabad') != -1 
)

Despite the initial approach working for non-null columns, it produces incorrect results when dealing with null valued columns.

this.filter = this.array.filter(i =>
      i["job"] != null ? i.job.toLowerCase().indexOf('ca') != -1 : false ||
      i["city"] != null ? i.city.toLowerCase().indexOf('ahmedabad') != -1 : false
    )

The current output is:

[ { "name": "Margie", "city": "Mumbai", "job": "CA" } ]

The expected output should be:

 [{ name: "John", city: "Ahmedabad", job: "IT" },
  { name: "Margie", city: "Mumbai", job: "CA" }]

You can find a detailed breakdown at this link: https://stackblitz.com/edit/filter-with-tolowercase-and-null?file=src/app/app.component.ts

Answer №1

After making a few modifications to your original code, I was able to obtain the correct answer:

this.filteredArray = this.originalArray.filter(item =>
  (item["job"] && item.job.toLowerCase().includes('ca')) ||
  (item["city"] && item.city.toLowerCase().includes('ahmedabad'))
)

Answer №2

When trying to filter an array based on specific conditions like job containing 'ca' or city being 'ahmedabad', it is important to pay attention to operator precedence in the code snippet provided below:

this.filter = this.array.filter(i =>
  (i["job"] != null ? i.job.toLowerCase().indexOf('ca') != -1 : false) ||
  (i["city"] != null ? i.city.toLowerCase().indexOf('ahmedabad') != -1 : false)
)

This issue arises from the sequencing of logical operators and evaluating conditions correctly.

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

Acquiring JSON-formatted data through the oracledb npm package in conjunction with Node.js

I am currently working with oracledb npm to request data in JSON format and here is the select block example I am using: const block = 'BEGIN ' + ':response := PK.getData(:param);' + 'END;'; The block is ...

What are the appropriate scenarios for extending and utilizing an abstract class in Angular?

@Component({ selector: 'my-component', template: `<ng-content></ng-content>`, providers: [ { provide: AbstractClass, useExisting: forwardRef(() => TargetComponent) } ] }) export class TargetComponent extends AbstractCla ...

"Upon clicking the login button, I encountered an issue with redirecting to the destination

I've been working on developing a login page using Angular framework. However, I'm facing an issue where I am unable to access the destination page after entering the login credentials. Below, you can find a snippet of the code from the login.com ...

Utilize multiple validators.patterns within a single value for enhanced data validation

I need to implement two different patterns for the formControlName='value' based on the type selected. If type is 'A', I want to use the valuePattern, and if type is 'B', I want to use the uname pattern. This is my HTML code: ...

What is the TypeScript term for assigning multiple parameters an alias?

Imagine having a piece of code structured like this: export async function execute(conf: Record<string, string>, path: string, params: Array<string>) { const cmd = params[1]; const commandOption = params.slice(2) switch(cmd){ ...

What is the best way to instantiate objects, arrays, and object-arrays in an Angular service class?

How can I nest an object within another object and then include it in an array of objects inside an Angular service class? I need to enable two-way binding in my form, so I must pass a variable from the service class to the HTML template. trainer.service. ...

Retrieve all values of a specific enum type in TypeScript

When working with Typescript, I am looking to retrieve all values of an enum type and store them in an array. In C#, a similar method would look like this: public static TEnum[] GetValues<TEnum>() where TEnum : Enum { return Enum.GetValues(typeof ...

Expanding the HTTP Get URL with a click in Ionic 2 and Angular 2

I recently performed a search for my ionic app, which fetches data from an api using a http get method as shown below static get parameters() { return [[Http]]; } searchRecipes(id) { var url = 'http://api.yummly.com/v1/api/recipes?_app_id=// ...

typescriptIn React Router v5 with TypeScript, an optional URL parameter is implemented that can have an undefined

I'm currently working with react-router v5.1 and TypeScript, and I have set up the following route configurations: <Router basename="/" hashType="slash"> <Switch> <Route path="/token/:tokenName"> <TokenPag ...

What is the process of incorporating a JavaScript node module into TypeScript?

Having trouble importing the xml2js module as I keep getting a 404 error stating that it's not found. import xml2js from 'xml2js'; Any suggestions on how to properly import JavaScript modules located in the node_modules directory when work ...

The depth buffer in Webgl FrameBuffer is not being cleared properly

Currently, I am working on developing a 2D sprite renderer that utilizes render textures for custom compositing. However, I have encountered an issue where the depth buffer on the FrameBuffer is not clearing properly. Due to this, all the sprites leave a p ...

Is it possible that jest is unable to catch the exception?

I have a simple function that looks like this: function foo({ platform }) { if (platform === 'all') { throw new Error('Platform value can only be android or ios'); } return `${platform}`; } After writing unit tests, the re ...

Uncovering the Full Scope of a LinkedIn Profile with Typescript

Hello, I am currently in the process of developing an Ionic2 framework app that includes social login functionality. Up to this point, I have successfully integrated Google Plus and Facebook buttons. Now, I would like to add LinkedIn login as well. The c ...

Strategies for Handling Errors within Observable Subscriptions in Angular

While working with code from themes written in the latest Angular versions and doing research online, I've noticed that many developers neglect error handling when it comes to subscription. My question is: When is it necessary to handle errors in an ...

What is the best way to convert the javascript code into clojurescript?

Looking to utilize capacitor/app in order to determine the state (background or active) of my iOS app. My project is built on Clojurescript, so I need to convert the following javascript code into a clojurescript equivalent. Javascript import { App } fro ...

Creating a custom decision tree in Angular/JS/TypeScript: A step-by-step guide

My current project involves designing a user interface that enables users to develop a decision tree through drag-and-drop functionality. I am considering utilizing GoJS, as showcased in this sample: GoJS IVR Tree. However, I am facing challenges in figuri ...

Obtain the parameters of a function within another function that includes a dynamic generic

I am attempting to extract a specific parameter from the second parameter of a function, which is an object. From this object, I want to access the "onSuccess" function (which is optional but needed when requested), and then retrieve the first dynamic para ...

The TypeScript in the React-Native app is lacking certain properties compared to the expected type

I recently integrated the https://github.com/react-native-community/react-native-modal library into my project and now I need to create a wrapper Modal class. Initially, I set up an Interface that extends multiple interfaces from both react-native and reac ...

Angular 2 TypeScript: Accelerating the Increment Number Speed

I'm working with a function in Angular 4 that is triggered when the arrow down key is pressed. Each time the arrow down key is hit, the counter increments by 1. In this function, I need to run another function if the counter reaches a certain speed. ...

Issue encountered while attempting to run an Angular project using the CLI: "Module not found - Unable to resolve 'AngularProjectPath' in 'AngularProjectPath'"

Just like the title suggests, I'm facing an issue with compiling my angular project. It seems to be having trouble resolving my working directory: Error: Module not found: Error: Can't resolve 'D:\Proyectos\Yesoft\newschool& ...