Verifying whether a new element already exists in a TypeScript array

In my programming class, I have defined properties like this:

id: number;
motorcycleId: number;
brand: string;
model: number;
year: string;
isDeleted: boolean;

Within my component, there is an array containing instances of this model:

motorcyclesList: MotorcycleModel[];

My goal is to implement a check to see if a new motorcycle being added already exists in the array.

        if (this.motorcyclesList.find(x => x.model === this.motorcycle.model &&
        x.motorcycleId === this.motorcycle.motorcycleId &&
        x.year === this.motorcycle.year)) {
        //some logic if exist
    }

But so far, the result is always false.

Answer №1

After taking into consideration the advice from @JB_Nizet and @Nitzan_Tomer, it is recommended to convert this.motorcycle.motorcycleId and this.motorcycle.model to numbers using the + operator:

 let exist :boolean =  this.motorcyclesList.some(x => 
      x.model === +this.motorcycle.model && 
      x.motorcycleId === +this.motorcycle.motorcycleId &&
      x.year === this.motorcycle.year
 );

// take action if exist is true 

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

Retrieving information from a JSON array in Unity using C#

I have been experimenting with using the OpenWeatherMap API in Unity C# alongside JSONUtility, and I am encountering an issue accessing the "weather" array (specifically the "main" attribute), while being able to access other data such as "timezone" and "n ...

I am attempting to store the primary array in local storage, but unfortunately, the value is not being saved within the React context API

I attempted to store the main array in local storage and retrieve it as global state, but I am facing an issue where the data is not being saved in the local storage. This file represents my context. import { createContext, useReducer, ReactNode, FC, use ...

What is the best way to convert a tuple containing key/value pairs into an object?

How can the function keyValueArrayToObject be rewritten in order to ensure that the type of keyValueObject is specifically {a: number; b: string}, instead of the current type which is {[k: string]: any}? const arrayOfKeyValue = [ {key: 'a', val ...

transitioning from angular 5 to the latest version of angular 7

After successfully migrating my application from Angular 5 to Angular 7, I made the necessary changes by replacing EventSource with EventSourcePolyfill as recommended during the application runtime. However, I am now encountering a peculiar issue. The cons ...

Combining arrays encoded in JSON format

Consider the following array examples: $array1 = [ 'test' => json_encode([ 'key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3' ]) ] Now, let's ...

What is the best way to utilize getters and setters for an array variable in order to retrieve specific array items by index rather than the entire array as a whole?

class CustomClass { var storedDates: [Date] { get { return cloudKitRecord.object(forKey: "dates") as! [Date] } set(newDates) { cloudKitRecord.setObject(newDates as! CKRecordValue, "dates") ...

Step-by-step guide on how to stop CDK Drop depending on a certain condition

I'm trying to figure out how to disable dropping using CDK based on certain conditions. Specifically, I want the drop functionality to be disabled if the list I'm attempting to drop into is empty. I haven't been able to find a solution withi ...

Clicking on an Angular mat-checkbox requires two clicks to toggle between checked and unchecked states

My checkboxes are populating dynamically, but I am facing an issue when trying to unselect them. It takes two clicks to uncheck the checkbox. enter code here <mat-tree [dataSource]="dataSource" [treeControl]="treeControl"> ...

Mapping the response from an http.get call to create a new typed object instance in Angular 2

Can anyone help me understand how to map the result from a service call to an object using http.get and Observables in Angular 2? Please check out this example In my getPersonWithGetProperty method, I am trying to return an Observable of type PersonWithG ...

Tips for connecting data to an HTML page with Angular 2

My code is throwing an error message while I'm debugging: Error: Uncaught (in promise): TypeError: Unable to get property 'standard' of undefined or null reference Here is the relevant part of my code: student.component.ts: this._studentSe ...

What steps must be taken to resolve the error of setting headers after they have already been sent to the client?

Got a couple questions here. I've been using the express get method for a search query and it's fetching the requested tickets without any issues. However, I keep encountering errors even though the method itself is functioning properly. So, my f ...

What is the method for implementing an Inset FAB with Material UI in a React project?

Currently, I am working on a project that requires an "Inset Fab" button to be placed between containers. After referencing the Material Design documentation, I discovered that the component is officially named "Inset FAB". While I was able to find some tu ...

What is the best way to arrange the information in JSON in ascending order and display it in a table format?

I am working with a mat-table and have used GET to display my data. I now want to sort the data in ascending order based on the db-nr from my JSON. Here is an excerpt from my JSON: { "period": 12.0, " ...

Using JQuery and Javascript to retrieve information from one drop down list based on the selection made in another drop down

I'm currently working on a project that involves 2 drop-down menus. The first menu allows you to select a general model, while the second menu displays specific models based on your selection. http://jsfiddle.net/QskM9/ Here's an example of how ...

Ways to avoid Next.js from creating a singleton class/object multiple times

I developed a unique analytics tool that looks like this: class Analytics { data: Record<string, IData>; constructor() { this.data = {}; } setPaths(identifier: string) { if (!this.data[identifier]) this.da ...

What is the most appropriate form to use, and what factors should be considered in determining

Incorporating generics in typescript allows me to create a generic function in the following manner: Choice 1 declare function foo1<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } Alternatively, I have the option to omit the seco ...

Is there a way to insert a secured page right before accessing the dashboard?

I am trying to create a locked page that will display a message when users access the web app from a mobile device and load a mobile layout page displaying a message like mobile is not supported. I was considering using document.addEventListener('DOMC ...

Preventing Event Loop Blocking in Node.js: The Key to Streamlining Performance

I am currently working on developing two APIs using Express.js. The tasks for both APIs are quite straightforward. The first API involves running a for loop from 1 to 3,000,000, while the second API simply prints a string in the console. All the necessary ...

Divide a collection of objects into groups based on 2-hour time spans

I have an array of objects that I need to split into chunks of 2 hours each, starting on the hour (e.g. 10.00 - 12.00, 12.00 - 14.00, etc). Here is my current solution, but I feel like it may not be the most efficient: Please consider the day variable, w ...

The specified 'IArguments' type does not qualify as an array type

Currently working on crafting a personalized logger. It's a fairly straightforward process, but I'm running into some errors that are muddying up my output. Here's what I have so far: @Injectable() export class Logger { log(...args: any ...