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

"Ensure that the data in the div is being updated accurately via AJAX in ASP.NET MVC

I'm currently using a div element to display data on page load through AJAX calls. $(document).ready(function () { email_update(); }); function email_update() { $.ajax({ url: '@Url.Action("EmailsList", "Questions")', ...

Every time I attempt to execute mupx deploy, an error message appears

issue in console shubhabrata@shubhabrata-VirtualBox:~/Meteor/myapp$ mupx deploy Meteor Up: Advancing Meteor Deployments for Production Configuration file : mup.json Settings file : settings.json “ Discover Kadira! A powerful tool to monitor yo ...

What could be causing my Express server to return a 404 error when trying to submit the form, all while failing to display any console

Having trouble setting up multi-user sessions similar to Google Docs, but my server file seems unresponsive. I've double-checked my fetch function and ensured it is accurate, yet no changes are occurring. Even console.logs from the server file command ...

React js: Changing Material-UI functional code to class component results in TypeError

After utilizing the material ui login page code, I discovered that it is a functional component. To meet my specific requirements, I decided to convert it into a class component. However, during the conversion process, an error was encountered: "Cannot ass ...

Combine arrays using underscore or lodash

Hello, I need some assistance. I have a couple of arrays containing grades with associated classes attributes like the examples below: var arr1 = [{ "id": 53, "name": "Grade 1 AppMonkeyzTest", "classes": [{ "id": 5 ...

Creating new Vue components is happening towards the end of the loop

I am currently encountering an issue with my Vue components. I have structured them in a hierarchy where I have a post-index component displaying all posts, containing a post-view component for individual posts, and within that, a post-like component to ha ...

Tips for showcasing timestamps within a Vue.js/Firebase application

In my current project, I am working on developing a chat application using Vue.js and Firebase. The codebase I am referring to can be found at https://github.com/jsfanatik/vuestacks-chat-vue-firebase. I have successfully implemented the Chat component to a ...

What are different ways to modify a bytearray within a file using angular js, whether it is an .xlsx or other

I received a bytearray response from my API that was converted from a .xlsx file. I now need to open or download this bytearray in the browser after converting it back to its original file extension. Can anyone provide guidance on how to achieve this? I ...

In Javascript, a variable is being defined by combining a string with another variable through concatenation

Hey, I'm relatively new to working with Javascript and am facing an issue that I believe can be resolved easily with the right syntax. The problem lies in setting a variable (totalRow1) where it needs to be concatenated with a string and another vari ...

What strategies can I use to refactor this controller in Angular 1.5 to make it more concise and efficient

I am encountering an issue with a component I have that contains a button. Whenever the button is clicked, it triggers one of two backend services depending on where the component is located. To achieve this, I am currently passing a flag to the component ...

transfer jquery element using jquery ajax

How can I send a jQuery object to a PHP function using POST? When I stringify the object, I get the following output: [ { "id": "701", "user_id": "2", "playlist": "ukg%20garage", "tracks": "5", "thumbnail": "Coldplay.jpeg", "crea ...

What is the best way to refresh a PHP function based on a JavaScript event?

I have a website where a div tag shows all the values from a SQL database using PHP. I want to reload this div tag with a JavaScript event, such as clicking on an HTML button. Is it possible to bring back all the values from the SQL database and display th ...

The jQuery Modal Dialog functions properly on the initial page load, but fails to work on subsequent pages unless manually refreshed

So, I've encountered an issue with my jQuery modal dialog. It's set up to remind non-registered users to sign up when they try to access user-only actions. Oddly enough, the dialog functions perfectly after a page refresh on THAT specific page. H ...

How can PHP effectively interpret JSON strings when sent to it?

When working with JavaScript, I am using JSON.stringify which generates the following string: {"grid":[{"section":[{"id":"wid-id-1-1"},{"id":"wid-id-1-4"}]},{"section":[{"id":"wid-id-1-5"}]},{"section":[{"id":"wid-id-1-2"},{"id":"wid-id-1-3"}]}]} I am ma ...

What is the process for executing PhantomJS commands through a NodeJs server?

My current challenge involves setting up a Node Server and incorporating PhantomJS commands within the NodeJS server. An example command includes: phantomjs phantom-server.js http://example.com Although I found some information related to this issue on ...

Using setInterval with Internet Explorer 10

In Internet Explorer 10, the setInterval function does not work properly. I have a web page where, upon form submission, a lengthy process is triggered on the server to download a file. To keep users updated on the progress, I utilize setInterval to repeat ...

Create a class for the grandparent element

Is there a way to dynamically add a class to a dropdown menu item when a specific child element is clicked? Here's the HTML structure I have: <ul id="FirstLevel"> <li><a href="#">FirstLevel</a></li> <li>< ...

Easy way to make a jQuery getJSON request to Twitter

After browsing through numerous Twitter and jQuery related questions, I have yet to find a solution to my specific issue. My goal is simple - to retrieve 5 "tweets" from a public user. At this stage, I am not manipulating the data in any way, but for some ...

If the width is below 767, the previous code will not be effective in jQuery

Challenge: How can I ensure that the code within the if statement only executes when the screen width exceeds 767px, and does not work if it is less than 767px? Using jQuery: $(document).ready(function() { $(window).resize(function() { if ($( ...

What is the best way to create an arrow connecting a parent div to multiple child divs?

I'm faced with a challenge involving a reusable React list component that supports nested children. My goal is to visually connect the parent div to its direct children using arrows, similar to the image linked below. View List Component Image Below ...