The best way to delete an item/object from ArrayList?


#1

Hello team! Im back!

From my yesterdays questions i’ve got another new , well those are pretty easy almost like yesterday ones which they got resolved with your help and my effort so first before all thank you!!!

I will explain my code now:

listaItems: any = [];

i have a provider where i share some items in an arraylist, this arraylist is called listaItems, there i save the exercise when the user presses a button and they get saved there without problem, there is my adding fuction:

 anadirItemLista(item) {
    this.listaItems.push(item);
    console.log(this.listaItems.length);
  }

pretty easy uh? Well now the problem comes when the user wants to delete that exercise, i thought on using the fuction splice because i didnt find a function like the “remove” function in java, the nearest was this “splice”, i saw that i need the index of the object in the arraylist so that i did:

 buscarIndiceDeItem(item) {
    var i = 0;
    var final = -1;
    this.listaItems.forEach(element => {
      i++;
      if (element.title == item.title) {
        //console.log("entramos aqui con i de " + i);
        final = i;

      }
    });
    return final;
  }

this function is called inside another:

 eliminarDeRutina(item) {
    var indiceABorrar = this.buscarIndiceDeItem(item);
    if (indiceABorrar != -1) {
      this.listaItems.splice(indiceABorrar, item);
      console.log("borrado con exito");
    }
    console.log(this.listaItems.length);
  }

i somehow get to delete all the items from the same type but i dont want that, i want to delete one item in particular, i got his index and everything just i dont know how to delete it from the arraylist itself!

IT should be easy , but im newbie… HELP!


#2

Could you provide the html where you display those items?


#3

is it late i already found a solution, not the cleanest and styliest one for sure but i will explain it now:

what i did it was get the this.listaItems array and make an auxiliar array, so now i have 2 arrays and one index

In the auxiliar i copy the same items from the original one except the indexed one so if i had an array of 4 items now i have another of 3 for example, the original one gets removed fully by doing:

this.listaItems=[]

and then i copy the items from the aux to the original one so now both have 3 items and the selected item got deleted, its simple way and not elegant at all im sure, but better than stuck and loosing time!!

Thank you for your answer anyway! :slight_smile: u keep want to see the html?


#4

You’re using the splice wrong. The second parameter of the splice method is the count of the delete/splice. So you should enter a numeric value there; 1.

Also, typescript has build in methods for finding an index of an object containing a specific value.

I’ve rewritten the code you’ve provided.

    private listaItems: IItem[] = [];

    constructor() {
        this.listaItems = [
            { title: "Name 1", value: true},
            { title: "Name 2", value: false},
        ]
        console.log(this.listaItems);
    }

    anadirItemLista(item: IItem) {
        this.listaItems.push(item);
        console.log(this.listaItems.length);
    }

    eliminarDeRutina(item: IItem) {
        console.log("Start");
        
        const indiceABorrar = this.listaItems.findIndex((i: IItem) => {
            return (i.title === item.title);
        });
        if (-1 != indiceABorrar) {
            this.listaItems.splice(indiceABorrar, 1);
            console.log("borrado con exito");
        }
        
        console.log(this.listaItems);
    }

Use this as refference.

A good Google search would have provided you with tonsss of working and clean examples.

Oh, and please don’t use that auxiliary array method unless you have a realll good reason to do so. Unnecessary for just this operation.

Good luck


#5

Btw.
I’ve created an Interface which is also cleaner to work with. Creating interfaces for your (data) objects will help you script faster and with less chance for errors.

I’ve created a folder for these; e.g.:
[root]/src/models/item.model.ts

export interface IItem {
    title: string,
    value?: any,
}

You can import the interface as always; e.g.:
import { IItem } from "../../models/item.model";


#6

You are the boss, that simple


#7

Incidentally, assuming you are using ngFor in the template, you can use the common idiom:

<div *ngFor="let hero of heroes; let i = index">
<button (click)="killHero(i)">

…to directly provide the index to your controller function, obviating the need to loop across searching for it.