Using a static value in the comparator is necessary for Array.find to function properly in Typescript

Looking to retrieve an item from an array:

const device = this.selectedDevtype.devices.find(item =>
    console.log(this.deviceID);
    return item.device_id === this.deviceID;
});
console.log(device);

When this.deviceID is logged, it shows "4", but the value of device comes back as undefined.

Log fail

However, if a hardcoded value like 4 is used, it works fine:

const device = this.selectedDevtype.devices.find(item =>
    console.log(this.deviceID);
    return item.device_id === 4;
});
console.log(device);

Log OK

Why does the first function not work? What could be causing this error?

I am using TypeScript version 2.6.2 and working on Angular 5.


Essentially, the issue lies in comparing a string and a number. I realized that I had declared the type in the component class:

deviceID: number;

The Angular Material radiogroup was converting the variable to a string:

<mat-radio-group [(ngModel)]="deviceID" (change)="updateDevice()">
  <mat-radio-button fxFlex="50"
    *ngFor="let device of selectedDevtype.devices" value="{{ device.device_id }}">
    [{{ device.key }}]{{ device.name }}
  </mat-radio-button>
</mat-radio-group>

This discovery might help someone facing a similar issue.

Answer №1

Could it be that you are inadvertently comparing a string to an integer?

Consider attempting the following:

const targetDevice = this.selectedDeviceType.availableDevices.find(deviceItem => +deviceItem.deviceId === +this.targetDeviceId)

Answer №2

There appears to be no instances where item.device_id equals 4.

When using the find() method, it will return the value of the first element in an array that meets the specified condition, else undefined is returned.

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

Preventing Past Dates from Being Selected in JQuery Date Picker

Need help with a date picker that only allows selection of the 1st and 15th dates of each month. How can I prevent users from selecting previous dates? <link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" ty ...

Center-align the text in mui's textfield

What I'm looking for is this: https://i.stack.imgur.com/ny3cy.png Here's what I ended up with: https://i.stack.imgur.com/vh7Lw.png I attempted to apply the style to my input props, but unfortunately, it didn't work. Any suggestions? Than ...

Create a JavaScript JSON object using a for loop

I am working on creating an object similar to this var flightPlanCoordinates = [ {lat: 37.772, lng: -122.214}, {lat: 21.291, lng: -157.821}, {lat: -18.142, lng: 178.431}, {lat: -27.467, lng: 153.027} ]; Here is my attempt so far for (i = 0; ...

What is the best way to manage communication with a database in a Node.js application?

I have a specific structure in my Express app: There is a db helper that I use to interact with my MariaDB database Here is the code snippet: var MariaSQL = require('mariasql'); var db = new MariaSQL(); var queries = { getUserByID : &a ...

Transmit data in the form of a buffer

const response = await client.render(data); const Writable = require('stream').Writable; var buffer = []; const myWritableStream = new Writable({ write(chunk, encoding, callback) { ...

Sending a post request to an Express.js API from a different device

I currently have a server running on localhost:3000, with my app.js set up to utilize the angular router. When attempting to access localhost:3000 in my browser (for example: app.use('/', express.static(path.join(__dirname, '/dist/Client&apo ...

Struggle between Angular and fundamental CSS principles

Upon following the steps below, I aim to achieve my desired grids: How to set auto-margin boxes in flexible-width design using CSS? The solution provided is effective when implemented outside of Angular. However, when inserted inside an Angular component ...

Tips for updating a single event in eventSource after it has been dragged and dropped in fullcalendar-angular

I have successfully set up the calendar using @fullcalendar/angular v4.2 and am fetching data from my backend API using eventSources. However, I am facing an issue with dragging events to a new date in the month view. <full-calendar #calendar ...

Encountering a CORS policy issue while attempting to retrieve data from an API

I have been attempting to retrieve data from the DHL API, however, I keep encountering issues due to CORS policy blocking the request. Even though I have configured the CORS policy on my backend server, the error persists. What could be the issue? Here ...

Is there a way to implement personalized error management in TypeScript with Express?

For a while now, I have been using JavaScript to create my APIs but recently made the switch to TypeScript. However, I keep encountering errors along the way. One particular error handler I have set up is for when a route cannot be found, as shown below: i ...

Steer clear of including numerous variable values in Angular 2 while adjusting the class of selected items

Here's a question from someone who is new to Angular 2 and looking for an efficient way to change the active CSS class of tabs without using the router: activeTab: string; switchActiveTab(newTab: string) { this.activeTab = newTab; } <div clas ...

Issue with displaying children in Angular 2 router: children components not appearing on the

I am currently in the process of incorporating a user authentication bundle into my Angular 2 project by following this tutorial at . I have organized all the files from the bundle into a parent folder named "loginMGR", and modified the module, components ...

Display user input within a modal dialogue box

I have a subscription form that requires users to enter their name and email address. After clicking on "Compete Now," a pop-up appears asking for workshop information and postal code. The form is functioning correctly as intended. However, I want the em ...

Visualizing JSON data in React.js using Chart.js

Currently, as a beginner in ReactJS, I am working on an application that displays COVID-19 data from a JSON API in a visual format using Chart.js. However, despite trying various solutions, I am unable to visualize the data. Below is my source code: App ...

Tips for persisting objects created in PHP while utilizing XMLHttpRequest

Currently, I am working on a web page with the index.php file structured as shown below: include('UserClass.php'); include('html/top.php'); $user = new User(); if (isset($_POST['user'], $_POST['pass'])) { $user-& ...

Inspect each page to confirm that the user has verified that they are of legal age

I'm currently developing a website (tobacco-related) that imposes an age validation requirement on all visitors before granting access to the site. I've implemented a form for age verification, but I'm stuck at how to store a cookie upon pas ...

Writing a function to determine if an HTML element is present

Is there a way to create a function that checks for the existence of an element with a specific id? I have a list of IDs stored in an array: let CartArray = ["cart-0", "cart-1", "cart-2", "cart-3"]; This is the Java ...

Innovative sound system powered by React

I am working on implementing a music player feature on a website where users can select a song and have it play automatically. The challenge I am facing is with the play/pause button functionality. I have created all the necessary components, but there see ...

Interface of TypeScript Undetermined

Currently, I am developing a Demo API Wrapper specifically for Roblox. During the development process, I have come across a certain issue that I would like to address. My aim is to send a request and then return all the data in the manner of an API wrapper ...

Best practices for implementing JavaScript in JSP pages

After researching various sources, I have come across conflicting opinions on the topic which has left me feeling a bit confused. As someone new to web programming using java EE, I am looking to integrate javascript functions into my code. It appears that ...