#Getting unexpected results...

5 messages · Page 1 of 1 (latest)

deft flower
#

I have the following code which can be slapped into a console if you want to replicate it.

let text = "Heavy Crossbow (Underwater)";
const allWeapons = ["Heavy Crossbow", "Heavy Crossbow (Underwater)", "Composite Longbow (+2 Str)"];
const lootedItems = text.split(';').map(item => ({ name: item.trim() }));

function getMatchingItems(lootedItems) {
  const matchingItems = {
    heavy_crossbow: 0,
    heavy_crossbow_underwater: 0,
};

  for (let i = 0; i < lootedItems.length; i++) { 
    const lootedItemName = lootedItems[i].name.toLowerCase();
    for (let x = 0; x < allWeapons.length; x++) {
        const weaponName = allWeapons[x].toLowerCase();
    const escapedWeaponName = weaponName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    if (lootedItemName.match(escapedWeaponName)) {
        if (weaponName === "heavy crossbow") {
                    matchingItems.heavy_crossbow++;
                } else if (weaponName === "heavy crossbow (underwater)") {
                    matchingItems.heavy_crossbow_underwater++;
                }
      }
    }
  };
  console.log(matchingItems)
};
const matchingItems = getMatchingItems(lootedItems);

The issue I'm facing this time is that when text is "Heavy Crossbow" the heavy_crossbow is 1 as intended. However, when text is "Heavy Crossbow (Underwater)" both keys are 1.

Any ideas how I can solve this?

crude birch
#

hey I can help you but can you explain what you are trying to do?

crude birch
#

you can use map on lootedItems and weaponName would just be whatever the map variable is called so if you used x=> it would just be x["name"].toLowerCase() and then you can use js if (weaponName === "heavy crossbow") { matchingItems.heavy_crossbow++; } else if (weaponName === "heavy crossbow (underwater)") { matchingItems.heavy_crossbow_underwater++; } this code that you had

deft flower
#

Well this is just a piece of my code. The rest formats it to a message.

text is just for ease of access to this example. The actual code rolls a number of dice and returns items, those items then turned into a string.

I want each item to be checked and set a number to how many times it appeared in the string. So for example if my string is: Knife, Sword, Sword, Crossbow, Javlin the output would be:

Knife x1
Sword x2
Crossbow x1
Javlin x1

crude birch
#

Oh ok yeah if you follow my second message you should be able to get those results