remove args from ana array in discord.js
Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error remove args from ana array in discord.js on this date .
i wanna remove an argument that i prevously added to an array with a command, the code i made:
const args = message.content.slice(prefix.length).split(/ +/); const command = args.shift().toLowerCase(); const multipleArgs = args.slice(1).join(" "); const banWordAdded = new Discord.MessageEmbed() .setColor('#42f59b') .setTitle("Ban word added:") .setFooter(multipleArgs) const banWordRemoved = new Discord.MessageEmbed() .setColor('#42f59b') .setTitle("Ban word removed:") .setFooter(multipleArgs) if (banWords.some(word => message.content.toLowerCase().includes(word))) { message.delete() message.channel.send("Don't say that!"); } else if (command === 'banword') { if (!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send("You can't use this command") if (!args[0]) return message.channel.send("Choose either add or remove") if (args[0] == 'add') banWords.push(multipleArgs) message.channel.send(banWordAdded) console.log("Array updated"); } else if (args[0] == 'remove') { delete banWords(multipleArgs) message.channel.send(banWordRemoved) console.log("Array updated")
It works just fine when adding a ban word, but when i wanna remove it the bot deletes the command message for containing the banword instead of removing it from the banWords array, like i do q!banword remove example and the message gets deleted
Answer
delete
is used to remove Object properties
, therefore it will not work on arrays. You can use Array.prototype.splice()
or Array filter()
method to accomplish this.
Method 1 .splice()
const indexOfWord = banWords.indexOf(multipleArgs); // finding the element in the arr if (indexOfWord == -1) return message.channel.send('word not found'); // if word isn't already in the array return banWords.splice(indexOfWord, 1); // removing the word // first parameter is the index of the element to remove, second one is the number of elements to remove.
Method 2 .filter()
const filteredArr = banWords.filter(x => x != multipleArgs); // filteredArr won't contain the words provided
I believe splice would be ideal for you as it doesn’t create a new array, instead it modifies the existing array. hope this helped