Exploring Discord.js: Sorting a Collection of Retrieved Messages Using .sort()

This is a code example I am working with:

.sort((a, b) => b.createdAt - a.createdAt)

After fetching and filtering messages from a channel (which has a total of 8 messages), the filter operation returns a collection that may not be sorted in order.

How can I organize my messages so that the given formula functions correctly?

(Please disregard the .first() in the provided screenshot)

The collection contains 4 messages, where using .first() simply retrieves the initial message. My objective is to extract values from all four messages for inclusion in my embed like this:

newchannel.fetchMessages().then(messages => {
    var valuesA = messages.filter(m => m.author.id === message.author.id).first();
    var valuesB = messages.filter(m => m.author.id === message.author.id).second();
    var valuesC = messages.filter(m => m.author.id === message.author.id).third();
    var valuesD = messages.filter(m => m.author.id === message.author.id).fourth();
    const embed = {
        "fields": [
            {
                "name": "Type of code:",
                "value": valuesA.content,
                "inline": true
            },
            {
                "name": "Type of code:",
                "value": valuesB.content,
                "inline": true
            },
            {
                "name": "Type of code:",
                "value": valuesC.content,
                "inline": true
            },
            {
                "name": "Type of code:",
                "value": valuesD.content,
                "inline": true
            }
        ]
    };
}

While this snippet doesn't contain the complete code or entire embed setup, it provides all necessary details.

If you have any queries, feel free to ask in the comments below.

Answer №1

When working with a Collection, keep in mind that it extends the type of a Map.

Unlike objects, the keys in a Map are ordered. This means that when iterating over it, a Map object will return keys in the order they were inserted.

One key difference between an object and a Map is that the latter maintains a specific order of its elements.

The Discord.js Collection provides a handy method called sort.

For example, if the return type of the fetchMessages function is a

Promise<Collection<Snowflake, Message>>
, after resolving the promise you should be able to sort by createdAt.

client.on('message', async function(msg) {
  let chan = msg.channel;
  let sortedMsgs = await chan.fetchMessages(option)
    .then(msgs => {
      msgs.sort((a, b) => b.createdAt > a.createdAt) 
    })
});

Please note: While I cannot test this code at the moment, it's worth mentioning that the exact format of the compareFunction is not clearly defined in the documentation – so the use of > may need verification.

Answer №2

After struggling for a few days and seeking assistance, I finally managed to resolve the issue on my own:

Instead of using .sort(), I opted to utilize values[number].content to access each message individually.

Here's the updated code that is now functioning:

newchannel.fetchMessages().then(messages => {
    var values = messages.filter(m => m.author.id === message.author.id);
    values = values.first(4);
    const embed = {
        "fields": [
            {
                "name": "Type of code:",
                "value": values[0].content,
                "inline": true
            },
            {
                "name": "Type of code:",
                "value": values[1].content,
                "inline": true
            },
            {
                "name": "Type of code:",
                "value": values[2].content,
                "inline": true
            },
            {
                "name": "Type of code:",
                "value": values[3].content,
                "inline": true
            }
        ]
    };
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message HMR Webpack was found to be invalid

When using Webpack, I keep encountering the following error message: Invalid HMR message, along with a lengthy JSON string. Unfortunately, I couldn't find any helpful resources to assist me in debugging this issue. Do you have any suggestions? I&apo ...

What is the best approach to tackle this design?

As a newcomer to React, I'm facing challenges in positioning components. The layout I envision is consistent across all pages, with certain elements remaining the same. Should I utilize a grid system for this design? How should I approach achieving th ...

Retrieving a result from a function call is a fundamental aspect of programming

I have a scenario where I am initiating a call from a controller within AngularJS. This call passes some data to a service in order to receive a response that needs to be conditionally checked. Controller patents.forEach(function(item){ // The "patents" ...

Navigating with Vue Router in a Nuxt JS vuex Store

In my app, I'm currently developing a login/register system using Firebase and Vuex for authentication and database management. Within Nuxt JS, I have implemented actions to create a user, log them in, and sign them out. After a successful registrati ...

Exploring the potential of utilizing functions in express.js to take advantage of the "locals"

Having experience with Rails/Sinatra, I am accustomed to using helper functions in my view files. However, incorporating this functionality into express.js has proven to be quite challenging. You can include locals automatically like this... app.set("nam ...

How can Angular hide a global component when a particular route is accessed?

Is it possible to hide a global component in Angular when a specific route is opened? For instance, consider the following code: app.component.html <app-header></app-header> <app-banner></app-banner> <!-- Global Component I w ...

When attempting to change the text in the textarea by selecting a different option from the dropdown list, the text is not updating

I am facing an issue with three multi-select dropdown lists. When a user selects options from these lists and then presses the submit button, the selected text should display in a textarea. However, if the user manually changes some text in the textarea ...

Arrange a div close to another div with the help of absolute positioning

My goal is to create a tooltip-like positioning for an element within the same container as another element. When clicked, this particular element will display a div containing a table. You can find the complete code here: http://jsbin.com/xihebol When s ...

Tips on preserving type safety after compiling TypeScript to JavaScript

TS code : function myFunction(value:number) { console.log(value); } JS code, post-compilation: function myFunction(value) { console.log(value); } Are there methods to uphold type safety even after the conversion from TypeScript to JavaScript? ...

Updating the options list of an Autocomplete component post-render: A step-by-step guide

I've encountered an issue with a function that retrieves a JSON array from a URL containing a list of options to be displayed in my Autocomplete component. function DisplayOptions() { async function GetOptions() { options_list = await fetc ...

Disregard keys with null values when making a post request using react and axios

As a beginner in JavaScript, I am facing an issue where I do not want to include keys with null values when sending metadata. For example, I should only send the filepath as it has a value, and omit tags and owner which are null. How can I achieve this? ...

Is it possible to enable a button as soon as input is entered?

I'm encountering a minor issue with my button's functionality. I am attempting to have the button enabled as soon as text input is entered into the text field, but currently it only becomes enabled after the focus has changed from the text field. ...

I am looking to incorporate automatic scrolling functionality into my RSS Feed

I'm in the process of developing an RSS feed for my website. My expertise in JS/jQuery is limited, so any assistance would be greatly appreciated. After utilizing Google's Feed API and creating my own RSS Reader Widget, I realized that it lacked ...

Unable to utilize a third setState function due to the error message indicating an excessive number of re-renders

My current challenge involves setting an initial state for my Hook. I have a clickable element that changes the state between Decreasing and Increasing upon click, and this part is functioning properly. However, I encounter an issue when attempting to defi ...

What is the best way to store a downloaded video from the server?

I am currently in the process of downloading a video from a server using JavaScript XHR (specifically Angular $http GET with response type 'blob'). My question is, how can I save this downloaded video to a Chrome application's local storage ...

Utilizing PHP to dynamically load HTML forms and leveraging JQuery for form submissions

I am currently facing a dilemma that I am unsure how to approach. It seems that JQuery requires unique ID's in order to be called in the document ready function. I use PHP to read my MySQL table and print out HTML forms, each with a button that adds a ...

Using PHP script to retrieve MySQL table values and dynamically update a live graph in a Javascript function

I've been researching similar issues for quite some time now, but to no avail. Currently, I'm utilizing Highcharts to update a graph every 3 seconds with the latest entry from a specific MySQL table. I am referring to the example Javascript code ...

Changing from a vertical to horizontal menu as the parent div is resized

I am looking for a solution to create a CSS effect or Javascript code that will hide a menu inside a div when the browser window or parent div is resized. I want to display another div with the same menu in horizontal orientation when the first one is hidd ...

If the number exceeds 1, then proceed with this action

I currently have a variable called countTicked, which holds an integer representing the number of relatedBoxes present on the page. I am in need of an if statement that will perform certain actions when the value stored in countTicked exceeds 1. if (!$(c ...

Complete loading of iframe content on Internet Explorer versions 8 and 9

Having an issue with the full loading of a page in IE8-9. I need to perform certain actions after the content within a div is fully loaded, but it seems that in IE8-9, the page fails to load completely. This is causing problems as my actions are dependent ...