How does excludeItems.indexOf(item.id) works?


#1

Im in Misty Island Mine, and i passed it but, i don’t understand what’s happening in the code.

Mainly, how do the peasants each gets assigned a different coin?
Don’t know if i can post my code, so that someone could help out with some comments,
I hope i’m clear enough…

var bestItem = this.findBestItem(peasant, claimedItems);
if(bestItem) {
               claimedItems.push(bestItem.id);
}

#2

The idea is that you search the bestItem for peasant #1, checking if it’s already on the excludedItems (=claimedItems) list. If it’s not on the list, then put it on the list (append) and go for it! Then you do the same for peasant #2, etc.

The main thing to learn here is that you can check your object (item) against a list. Here is a different use of the same concept:

if enemy.type in ["thrower", "shaman", "fangrider"]:
    # do this
else:
    # do that

Cheers


#3

@ant Your answer explains the concept well, but I believe the OP is specifically asking about the JavaScript way of putting that concept in practice.

To answer the question in the title:

How does excludeItems.indexOf(item.id) works?

The array indexOf method searches the array for the given element and returns its index in the array. E.g.:

var arr = ['a', 'b', 'c'];
arr.indexOf('a') === 0; // array indexes start at 0
arr.indexOf('b') === 1;
arr.indexOf('c') === 2;

When the element is not found, the return value is -1:

var arr = ['a', 'b', 'c'];
arr.indexOf('d') === -1;

So, in order to check if an array contains a given element, you can use the indexOf method and check if the result is different or larger than -1.

When in doubt, you can always consult the MDN JavaScript documentation: Array.prototype.indexOf()


For a bit of trivia, you may wonder: "Can’t this be done in a simpler way?"
Well, yes, there is a proposal for an includes method to be added to the language, but it may take a while until it is fully standardised and get wide browser adoption.

I also recommend checking the motivation for the Array.prototype.includes proposal, which also explains how indexOf is currently used for this purpose.


#4

sorry for a late response, i just thought it would be polite to thank you for your time in answering the question…
It’s true i was interested in the aspect that UltCombo covered, but thank you ant for answering anyways!

Cheers,

naive