SirBT
SirBT

Reputation: 1698

How do I correctly use indexOf() with several elements?

I have an array of

var clickedImages = Session.get('clickedImages'); 
clickedImages = clickedImages.map( function(a) {return a.imageId;});

console.log("clickedImages Ids are: " ,...clickedImages);

Which yields:

clickedImages Ids are: TaTg6hf3Gok5NsWYp XzGxS3LDtJ4DrXSdc 8CdapJoeSxSScHKFs

var TotalOfallImageIds =  buyList.find().fetch().map(function(u) { return u._id; });
console.log(TotalOfallIds); 

Which yields:

["yzML7ZLvkWkjBBvq5", "XzGxS3LDtJ4DrXSdc", "TaTg6hf3Gok5NsWYp", "8CdapJoeSxSScHKFs"]

However when I run the code below, why do I get a false?

(TotalOfallImageIds.indexOf(clickedImages) > -1); 

The code above yields: false

How do I correctly use indexOf() with several elements?

Upvotes: 0

Views: 88

Answers (2)

Fred Johnson
Fred Johnson

Reputation: 2695

.indexOf is for comparing an item, so instead you need to iterate over one array and indexOf with the other

var allClicked = true;

for (var i = 0; i < clickedImages.length; i++) {
    var clickedImg = clickedImages[i];
    allClicked = TotalOfallImageIds.indexOf(clickedImg) > -1 && allClicked;    
}

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075587

Because there is no entry in TotalOfallImageIds that is === the array of clicked image IDs referenced by clickedImages. No array is ever === to a string (because the result of === is always false when the operands are not the same type). indexOf uses === for comparisons.

Upvotes: 1

Related Questions