Arranging the properties of an object following the reduction process

I am currently working on replicating the functionality of an Outlook mailbox by organizing a list of Outlook emails based on their conversation ID. However, I am facing the challenge of needing to sort my list twice - once to order the emails in each group from newest to oldest, and then to sort the conversation list itself from oldest to newest. This requires comparing the first item in each array (which should be the newest once sorted) to achieve the desired outcome.

Here is how the object looks once grouped:

{"sdfjskldfjks" : [{from: "joe", received_date:"07/11/1990 5:30PM"}], "dfjsakldfjhsa" : [{from: "john", received_date:"07/12/1990 5:30PM"},{from: "jake", received_date:"07/12/1989 5:30PM"}]}

Below is the function I am using to group the emails:

  const cleanFolder = computed(() => {
    if(currentFolder.value == null){
      return []
    }
  
    function groupBy(arr: any[], property: string) {
        return arr.reduce(function (memo: { [x: string]: any[]; }, x: { [x: string]: string | number; }) {
            if (!memo[x[property]]) { memo[x[property]] = []; }
            memo[x[property]].push(x);
            return memo;
        }, {});
    };

    return groupBy(currentFolder.value.emails,'conversation_id')
  })

Although I am familiar with sorting arrays, I am struggling to sort based on an object as seen in this case. Any guidance or suggestions would be greatly appreciated!

Answer №1

To begin, it is important to organize emails by their respective conversation_id. Then proceed to Sort each conversation group based on the received_date. Finally, sort the conversations based on the received_date of the newest email within each group. Follow the order outlined in the cleanFolder() function.

For further clarification, refer to the code snippet provided below:

const emails = [
    { from: 'joe', received_date: '07/11/1990 5:30PM', conversation_id: 'sdfjskldfjks' },
    { from: 'john', received_date: '07/12/1990 5:30PM', conversation_id: 'dfjsakldfjhsa' },
    { from: 'jake', received_date: '07/12/1989 5:30PM', conversation_id: 'dfjsakldfjhsa' }
];

function groupBy(arr, property) {
    return arr.reduce(function (memo, email) {
        if (!memo[email[property]]) { 
            memo[email[property]] = []; 
        }
        memo[email[property]].push(email);
        return memo;
    }, {});
}

function sortEmailsByDateDescending(emails) {
    return emails.sort((a, b) => new Date(b.received_date) - new Date(a.received_date));
}

function sortConversationGroupsByNewestEmailDate(conversationGroups) {
    return conversationGroups.sort((groupA, groupB) => {
        const newestA = new Date(groupA[0].received_date);
        const newestB = new Date(groupB[0].received_date);
        return newestA - newestB;
    });
}

function cleanFolder() {
    if (emails.length === 0) {
        return [];
    }
    const groupedEmails = groupBy(emails, 'conversation_id'); // group from conversation_id
    let conversationGroups = Object.values(groupedEmails);
    conversationGroups = conversationGroups.map(sortEmailsByDateDescending);
    conversationGroups = sortConversationGroupsByNewestEmailDate(conversationGroups);

    return conversationGroups;
}

console.log(JSON.stringify(cleanFolder()));

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

What steps do I need to take to have the button conceal all unfinished tasks?

Here is the link to my Jsfiddle code snippet: https://jsfiddle.net/zxo35mts/1/ I am attempting to create a button that will hide all incomplete tasks when clicked, and then show them again when clicked again. However, I am struggling with figuring out how ...

What is the best way to retrieve Firebase data and assign it to a variable in React after using setState

Working with react and firebase real-time database for the first time has been quite challenging. I'm struggling to extract the data and insert it into a constant called items. It seems like the firebase code is asynchronous, which means it executes a ...

What is the process for extracting information from one table based on a column's data in another table?

Let's consider two tables: Table 1 id | email 1 | email1 2 | email2 Table 2 userid | username 2 | user1 3 | user2 Now, with the help of sails.js associations, here is what I aim to achieve: I have a username = user1. What I need to a ...

What are some strategies for implementing dynamic script generation within an AJAX response?

I am exploring a new AJAX design approach where a script is returned to handle and show data. The JSON response below is currently functional, but I would appreciate advice on how to better organize the application for future maintenance. { payload: " ...

How can I create a custom elevation for a Vuetify v-menu?

I'm currently working with vuetify and v-menu as outlined in the official documentation here https://vuetifyjs.com/en/components/menus/ I'm struggling to figure out how to apply elevation only on the bottom left and right corners. When I add a ...

Responsive menu is failing to respond to the click event

I'm facing an issue with my responsive menu on mobile phones. It should display two buttons - one for the navigation bar and the other to toggle the side bar by removing the classes hidden-xs and hidden-sm. However, I am having trouble getting the btn ...

What is the process for converting a JSON File into an array using javascript?

Hey there, I'm new to programming so please bear with me XD. I've been struggling for 2 days trying to figure this out with no luck. So here's the deal - I have a chart in JavaScript that is pulling data from a file called test.json, which ...

Having trouble getting Jest to manually mock in Nestjs?

When setting up a mock service like this: // /catalogue/__mock__/catalogue.service.ts export const CatalogueService = jest.fn().mockImplementation(() => { return { filterRulesFor: jest.fn().mockImplementation((role: Roles): Rule[] => rules.filt ...

Retrieving Information from Website Components in JavaFX Web View

I am currently developing a Java FX program that loads a folder containing HTML/CSS/JS files with 3 different websites. While the websites are displaying correctly in the webview, I am looking for a way to capture user interactions, such as checkbox selec ...

Problem with nesting lists in VueDraggable

I am looking to incorporate the VueDraggable library into my project in order to create nested lists. I followed the documentation to create a component, and everything is working well except for one issue: I am unable to create new nested items. The onl ...

`My jquery mobile application fails to trigger the pageinit or ready events`

My website consists of 3 PHP pages: one index page and two subpages for sales and products. The index page has links to these subpages. When I click on the sales link, it is supposed to load sales data either on pageinit or document ready. However, no code ...

Enable lodash access throughout a React Native application

Is it possible to have lodash automatically accessible in all files within a React Native project without needing to import it every time? ...

Assistance with Validating Forms Using jQuery

I have a form located at the following URL: . For some reason, the form is not functioning properly and I am unsure of the cause. Any suggestions or insights on how to fix it? ...

Transfer information between two devices remotely through AJAX

I am in the process of developing a web application that utilizes a mobile phone as a controller, similar to this example: . The concept is quite simple - I just need to transfer text entered on the phone to the computer. There is no need for a database, ...

I believe I may be experiencing an issue with the use of 'style.display' in JavaScript

I'm encountering a small issue. I need a button to reveal more content. Therefore, I require a way to hide this content initially and display it upon clicking, with the ability to reverse this action by hiding it again. Despite my efforts, the conten ...

In React js, what is the best way to retrieve the first unique ID element as well as the last unique ID element from an

Hey there, I'm working with some data and you can find the link to it here: https://stackblitz.com/edit/react-26pgys. My goal is to filter the JSON and extract the first unique ID along with the last unique ID. I've already made an attempt at fi ...

`meteor.js and npm both rely on the fs module for file

I'm feeling a bit lost, as I need to use the fs package with Meteor.js framework. Starting from meteor version 0.6 onwards, I know that I should use Npm.require in the following way: var fs = Npm.require('fs'); However, when I try this, a ...

The website on iPad automatically zooms in upon opening and then increases the zoom level even further when a specific button is tapped

I recently coded a website using html, css, and js. It seems to work perfectly on all devices except for the iPad. Interestingly, when I use the iPad emulator in Google Chrome, everything appears normal. However, when I open the website on an actual iPad, ...

The inability to read property 0 of undefined persists despite implementing conditional rendering

I'm struggling to understand what mistake I'm making in the current situation: There's an array named arrayOfChildren that gets initialized like this: const [arrayOfChildren, setArrayOfChildren] = React.useState([]) With a handler function ...

The error message "Multiple children error occurs when an empty link in Next.js

Is there a way to successfully implement a <Link /> element without any content inside it in my application? Surprisingly, when I don't provide any content, I encounter the multiple children error, even though the opposite seems to be happening. ...