How to search for an object in Array?


What I want to achieve is, look for an object in array . Always return -1 whatever you want to say that you can not find any match in array to get your index and then delete that element.

I print the array twice, the first to make sure that the object to be searched is in the array and the second to make sure that it has been deleted, but the object is still there.

I've tried it with pure strings, and it works, but when I search for a complete object I do not ... Any suggestions?

deleteProductFromPurchase(name:string) {
   const index: number = this.array.indexOf({idCustomer: 998, idProduct: 664, name: "Montaña", price: 200});
   this.testArray.splice(index, 1);
asked by JGuerra 01.03.2018 в 16:45

2 answers


Final answer:

var index:number = this.array.indexOf(this.array.find(x => x.idP == id));

this.array.splice(index, 1);

Pimer I look for the complete object in array . Then that found object is passed as a parameter to the% indexOf to find the index of the complete object; and that, finally delete the desired object from array .

answered by 01.03.2018 / 19:19

You can fill find

this.array.find(x => x.idCustomer == 998);

or filter

this.array.filter(x => == this.personId)[0];

In this case the index [0] is in case there is a match or find many only bring the first, if you want to find many more in the array, you can remove the [0]

answered by 01.03.2018 в 16:47