flagarium
flagarium

Reputation: 9

discord.js TypeError: fn is not a function

I'm trying to make an array with the IDs of channels found with the names of channels from another array, but it returns the error "TypeError: fn is not a function". This is the relevant code.

    var filtered_channel_ids = [];
    filtered_channel_names.forEach(element => filtered_channel_ids.push(client.channels.cache.find(element).id))
    console.log(filtered_channel_ids);

Upvotes: 0

Views: 243

Answers (1)

Lioness100
Lioness100

Reputation: 8402

Collection.prototype.find() requires a function. For example:

collection.find((element) => element.name === 'Hello World')

However, element is a string (or so I assume, you haven't shown the filtered_channel_names array). It looks like you want to find a channel by it's name, for which you can use something similar to the function above.

client.channels.cache.find((c) => c.name === element).id

In addition, there are several optimizations you can make to your code. First of all, you can use Array.prototype.reduce() instead of forEach().

Also, since channels are mapped by their ID, you can use findKey() instead of find() to automatically return the channel id.

// original
var filtered_channel_ids = [];
filtered_channel_names.forEach(element => filtered_channel_ids.push(client.channels.cache.find(element).id))
console.log(filtered_channel_ids);

// new and improved
var filtered_channel_ids = filtered_channel_ids.reduce((acc, name) => 
  acc.push(client.channels.cache.findKey((c) => c.name === name), [])
console.log(filtered_channels_ids)

Upvotes: 1

Related Questions