2 Replies Latest reply on Sep 17, 2008 10:13 PM by wesm9787

    Sorting a Numerical Array by Variable Name

    wesm9787
      I'm creating a game and am in the middle of creating an inventory system, and I have an array for all of my items and an array for how many of each item is currently held. I then have a set of text boxes that I assign the item names and quantities to with a for loop. I need to constantly sort these arrays as new items are added to keep the items in order, but when the quantities array is sorted it throws everything off and all my quantities end up matching up with the wrong items. What I need to do is sort them by variable name so that itemArray(item1, item2, item3) matches up with itemQArray(item1.quantity, item2.quantity, item3.quantity). Is this even possible or will I have to rework my inventory system without the arrays?
        • 1. Re: Sorting a Numerical Array by Variable Name
          Rothrock Level 5
          I would rework them so that it was an array of objects:

          inventoryArray.push({item:"Item 1",qty:5});
          inventoryArray.push({item:"Something else",qty:2});

          That way you can sort and keep things together. You can sort like this:

          inventoryArray.sortOn("item", Array.ASCENDING);

          Or whatever you need. And you get the items like this:

          trace("The item "+inventoryArray[0].item)
          trace("The quantity "+inventoryArray[0].qty)

          • 2. Re: Sorting a Numerical Array by Variable Name
            wesm9787 Level 1
            Thanks, I had no idea you could even do that. Now I just have to write a function to rebuild the inventoryArray every time an item is found so it'll update the number of items owned when an item is found that's already in the inventory. Other than that everything works perfectly now.