Search code examples
discord.jsinventoryquick.db

How can I make it where if you have multiple of an item, it shows like "Fishing Pole (x3)"? [Inventory Command]


One question, how can I make it where if you have multiple of an item, it shows like "Fishing Pole (3)"? << change the 3 to for number of items

Since Discord will return with an error if the embed reaches over the max size. Thanks!

Inventory Code:

const db = require('quick.db');
const Discord = require('discord.js');

module.exports = {
    name: "inventory",
    description: "View your inventory",


    async run (client, message, args) {
        let items = await db.fetch(message.author.id);
        if(items === null) items = "Nothing"

        const Embed = new Discord.MessageEmbed()
        .addField('Inventory', items)

        message.channel.send(Embed);
    }
}

TL;DR How to remove duplicated items and put the number of items next to the item.


Solution

  • You basically need to transform your items data structure into some other data structure that is organized by the type of item. But we don't know what the heck 'items' is. Here is but one possible example. Assuming your inventory is an array of objects, you could do something like:

    var items = [{name:'fishing pole'}, {name:'sword'}, {name:'fishing pole'}, {name:'fish'}, {name:'fish'}, {name:'fishing pole'}];
    console.log('Disorganized:', items);
    
    var inventoryMap = new Map();
    
    items.forEach(function(item, index, array) {
      var itemArray = inventoryMap.get(item.name);
      if (itemArray) {
        itemArray.push(item);
      } else {
        inventoryMap.set(item.name, [item]);
      }
    });
    
    console.log('Sorted:');
    
    inventoryMap.forEach( function(value, key) {
      console.log(key, '('+value.length+')');
    });