indexOf is not wokring during search the object in array in ionic3?


#1

Hello
i have to get the indexOf selected Object but i got every time return -1 tell me whats the wrong in my code?

	addOrRemoveSubcategory(event:any, subCategroyObject: any) {
		//For firestore - Here we will hold the subcateoryObject and push into array 
		this.checkedCategoryObject = {
			"id"                 : subCategroyObject.keyId,
			"subCategoryName"    : subCategroyObject.subCategoryName
		}
		
		if(event.checked) {
			this.selectedSubCategoryKeyId = subCategroyObject.keyId;
			//Push only if not eixst in the array
			if(this.selectedSubCategoryArray.indexOf(this.checkedCategoryObject.id) == -1){
				this.selectedSubCategoryArray.push(this.checkedCategoryObject);
			}
		} else {
			this.selectedSubCategoryKeyId = subCategroyObject.keyId;
			var index         = this.selectedSubCategoryArray.indexOf(this.checkedCategoryObject);
			this.selectedSubCategoryArray.splice(index, 1);
		}
	}
![Screenshot%20from%202018-05-07%2010-15-48|690x307](upload://2pwnEg3Amc3bgYAK5bbs6U1mfxC.png)

#2

You search for an id while your array is a collection of object, so it tries to compare an object to an number => will never works, product -1.
You should use findIndex as follows:

let m = [{key:2,val:‘aaa’},{key:5,val:‘bbb’}];
let i = m.findIndex(item=>{return item.key==5});
console.log('i: ',i);


#3

sir i m using this but i got error findIndex of undefined
var i= this.selectedSubCategoryArray.findIndex(item=>{return item.id});


#4

I can only guess that this member variable (this.selectedSubCategoryArray) was never initialized with [] or new Array.
In your constructor code, initialize this member variable.


#5

Would suggest u to use lodash


#6

@Roye:-
Sir i have already initialized array in the constructor ?


#7

If you wish, you can share you code, and we can take a look.


#8

Should be:
var i= this.selectedSubCategoryArray.findIndex(item=>{return item.keyId==this.checkedCategoryObject.id});