Delete item in Typescript interface array when item is found, consistently showing a negative index

Here's the scenario:

export interface ISchoolsPreview {
    // Shared
    AgeID: string;
    School_name?: string;
}

A Checkbox change triggers a function:

onChange(code: string, name: string, check: boolean): void {
    const tempPreview: ISchoolsPreview = {AgeID: code, School_name: name};

    if (check) {
      this.schoolsPreview.push(tempPreview);

    } else {
      //This is where I encounter an issue
      const index = this.schoolsPreview.indexOf(tempPreview);
      if (index > -1) {
        this.schoolsPreview.splice(index, 1);
      }

    }
}

The 'check' variable determines whether to add or remove an element from schoolsPreview based on checkbox status. Adding works fine but when trying to remove, indexOf(tempPreview) always returns -1 even with the same entry passed.

How can I properly delete an element from my Interface List?

Answer №1

It is always recommended to find the index of an object based on a specific property within the object rather than using the entire object itself. This can be achieved with the following code snippet:

const index = this.schoolsPreview.findIndex((obj) => obj['Property'] === code);

If you anticipate having duplicate codes in the array, it may be necessary to generate unique ids for each object and search based on those ids.

Please Note: There is some uncertainty regarding passing objects to index, as it may only return true if the object references the same memory address. If you are searching for a new object that exists in a different memory location, it could potentially return false. Corrections or clarifications on this matter are welcome.

Answer №2

The issue was resolved by updating the code as follows:

  const index = this.schoolsPreview.indexOf(tempPreview);

changed to:

  const index = this.schoolsPreview.findIndex(s => s.AgeID === code);

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

Error: Unable to load L.GeometryField constructor in django-leaflet library

I'm having trouble saving a geolocation to a Postgres database using Django-leaflet. I keep getting an error message that says Uncaught TypeError: L.GeometryField is not a constructor. My code involves AJAX calls. <script> var csrftoke ...

My node.js and express application is encountering an issue where it is failing with an error indicating that a variable has not been

Currently in the process of understanding how node.js and express operate. I've successfully extracted data from my mongo database... and now I'm experimenting with transferring data between my router code and views. The locations.js file within ...

What is the best method for validating variadic mapped tuple arguments while maintaining the inferred generic types?

My situation involves a higher order function called `createHandler`, which takes rest arguments in a variadic mapped tuple format and maps them to a generic object type (let's call it `ObjA<>`). The function returned can then be passed to anoth ...

What is the reason behind a PHP page refresh causing a session variable to be released

In an attempt to unset a session variable after 2 minutes using unsetsession.php, I have the following code: <?php session_start(); if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120 ...

Flashing Screens with Ionic 2

I am currently dealing with a situation where my login page and homepage are involved. I have implemented native storage to set an item that helps in checking if the user is already logged in (either through Facebook or Google authentication). The logic fo ...

The weather app on my webpage is not showing any data

A weather application is currently in progress, but I am encountering issues with the display of temperature, country, and current weather description. It seems that the problem emerges after the HTML geolocation function. I suspect that the function is ha ...

Utilizing Axios to Fetch Data from an External API in a Next.js Application

I'm looking to retrieve data from an API and display it on a webpage. My application has API routes set up. Within api/apps/get-apps.js: import { APPS_PATH, BASE_URL } from '../constants/api.constants'; import axios from 'axios'; ...

Having trouble locating images and JavaScript files on GitHub Pages

Using a template from this source to create a react website with interactions involving smart contracts, I successfully got everything up and running smoothly on my localhost. All the features of the site were functioning correctly and images were displayi ...

Discovering uncategorized elements using javascript

Let's say I have a piece of HTML with some content that is not wrapped in any tags, like this: <html> <body> <p>text in a tag</p> other text outside any tag </body> </html> Is there a way to access the untagged el ...

Exploring MongoDB's $in and $ne Operators

Looking to retrieve some Documents based on a field that may exist in an array if a filter is applied. However, I also need to ensure that the same field does not equal null unconditionally. While using $in: [some values] can prevent null from being includ ...

What is the best method for incorporating the three.js GLTFExporter into a TypeScript project?

I have been exploring the use of GLTFExporter in a three.js project written in TypeScript. I started with a basic template from https://github.com/pinqy520/three-typescript-starter and made modifications to the render function as follows: console.log(`typ ...

Dealing with Javascript dependencies post bundling: Best Practices

My understanding is that when deploying a Javascript app, it's common practice to gather all dependencies and consolidate them into one file (which is then minified). However, I'm unclear on how the code I've written will be able to locate t ...

Performing an AJAX POST request using AngularJS

As I dive into AngularJS, one challenge I've encountered is integrating an AJAX call into my controller.js file. I've already managed to get the login controller up and running with the same service as this one. Now, my goal is to fetch data fro ...

The display function in Javascript has a tendency to work sporadically

I’ve been tasked with creating my own tic tac toe game through coding. While I am relatively new to programming, I have a strong passion for it. At the moment, I've set up a basic function to hide only the "O", leaving only the "X" visible on the gr ...

Transform an Excel spreadsheet into Json format effortlessly with Kendo's powerful tools

My upload feature allows users to upload an Excel sheet, and the backend API expects the data in JSON format. Here is an example of the expected input: [{ "LineNumber": "1", "Parma": 123, "PartNumber": 234, "Tes ...

Guide on how to execute an API request prior to rendering a component in React JS

export default function Dashboard(){ useEffect(() => { setTimeout(()=>console.log("API Call Completed"),5000) },[]) return( <div> <h1>Dashboard</h1> </div> ...

It appears that the observable form callback is only triggered a single time

Let me give you a little background information - I have developed an app that relies heavily on websockets for communication. In order to establish the socket connection, I need to retrieve a token from local storage and then authenticate against the serv ...

How do I implement an onClick event for an antd message component?

I have a question and I'm hoping for some help. Here is the code snippet in question: const [msgTimer, setMsgTimer] = useState(5); message.error('some error msg', msgTimer); In the antd documentation, the message component has an onClic ...

Issue with the footer occurring prior to displaying the content

After trying numerous solutions like flexbox and positioning, I still can't figure out how to place my footer component at the bottom before the container component is rendered. With an asynchronous data spinner loading above it, the layout looks quit ...

Python: Exploring and Modifying a Matrix in Python

I have a new inquiry regarding lists, specifically 2D lists. I attempted to modify the values in a list using the method provided to me previously, but it seems to be ineffective when applied to a 2D list. Here is the code snippet: fruits = [ ["Banana ...