Home > Net >  Filter duplicates in an array and listing as x2?
Filter duplicates in an array and listing as x2?

Time:08-05

I have an Inventory command for my discord bot that fetches items form the user's database and lists them, but it lists them as in the example

How would i go on about listing them as bread x2 or x3 as the user buys more bread?

Inventory command code if needed:

const { Client, Message, MessageEmbed } = require('discord.js');
const { QuickDB } = require('quick.db');
const db = new QuickDB();

module.exports = {
    name: 'inventory',
    aliases: ['inv'],
    /** 
     * @param {Client} client 
     * @param {Message} message 
     * @param {String[]} args 
     */
    run: async(client, message, args) => {
        let items = await db.get(`items_${message.author.id}`)
        let user = message.author;
        if(items === null) items = `Nothing Yet`;
        let embed = new MessageEmbed()
            .setColor("#2F3136")
            .setAuthor(`${user.tag}'s Inventory`, user.displayAvatarURL({ dynamic: true }))
            .setDescription(`\`\`\`${items}\`\`\``);
        message.channel.send({embeds: [embed]})
    }
}

CodePudding user response:

You could use a .reduce() to count the items and then map each item with count to a string:

const string = Object.entries(
  ['bread','bread','egg','milk','egg','bread']
    .reduce((res, item) => {
      res[item] ? res[item]   : (res[item] = 1);
      return res;
    }, {})
  )
  .map(([name, count]) => `${name} x${count}`)
  .join(', ');

console.log(string);

  • Related