Organize array of objects based on their respective dates

When fetching tasks from the API, I receive both active and completed tasks. My goal is to restructure this data to be compatible with SectionList in React-Native, organizing tasks based on their creation date (dataCadastro) so that they can be separated by day. You can refer to the documentation here: https://reactnative.dev/docs/sectionlist

{
  active: [
    {
      id: 1,
      dataCadastro: '2020-06-15T14:33:45.4807609+00:00',
      status: 1,
      description: '',
    },
    {
      id: 2,
      dataCadastro: '2020-06-15T15:33:45.4807609+00:00',
      status: 1,
      description: '',
    },
  ],
  completed: [
    {
      id: 3,
      dataCadastro: '2020-05-19T14:33:45.4807609+00:00',
      status: 1,
      description: '',
    },
    {
      id: 4,
      dataCadastro: '2020-05-19T15:33:45.4807609+00:00',
      status: 1,
      description: '',
    }
  ]
}

The desired outcome would look like this:

const dataTest = [
    {
      title: '2020-06-15', // All tasks for the 15th of June.
      data: [
        {
          id: 1,
          dataCadastro: '2020-06-15T14:33:45.4807609+00:00',
          status: 1,
          description: '',
        },
       {
          id: 2,
          dataCadastro: '2020-06-15T15:33:45.4807609+00:00',
          status: 1,
          description: '',
        }
      ],
    }, {...}  
  ];

Answer №1

The initial step is to combine all the available information.

const combinedTasks = data.active.concat(data.completed);

Following that, you must organize them based on their respective dates.

const organizedData = combinedTasks.reduce((organizedData, task) => {
    const date = new Date(task.createdDate.toLocaleDateString());

    if (!organizedData[date]) organizedData[date] = { name: date, info: [] };
    organizedData[date].info.push[task];
    return organizedData;
}, {});

Finally, the structured data needs to be converted into an array and arranged chronologically.

const sortedData = Object.values(organizedData).sort((a, b) => a.title - b.title);

Answer №2

If the data within active and completed are similar in type, you can easily map it by extracting entries:

var obj = { active: [ { id: 1, dataCadastro: '2020-06-15T14:33:45.4807609+00:00', status: 1, description: '', }, { id: 2, dataCadastro: '2020-06-15T15:33:45.4807609+00:00', status: 1, description: '', }, ], completed: [ { id: 3, dataCadastro: '2020-05-19T14:33:45.4807609+00:00', status: 1, description: '', }, { id: 4, dataCadastro: '2020-05-19T15:33:45.4807609+00:00', status: 1, description: '', } ]};

var result = Object.entries(obj).map(([_,data])=>({title: data[0].dataCadastro, data }));

console.log(result);

Otherwise, if they are not of the same type, you can utilize reduce:

var obj = { active: [ { id: 1, dataCadastro: '2020-06-15T14:33:45.4807609+00:00', status: 1, description: '', }, { id: 2, dataCadastro: '2020-06-15T15:33:45.4807609+00:00', status: 1, description: '', }, ], completed: [ { id: 3, dataCadastro: '2020-05-19T14:33:45.4807609+00:00', status: 1, description: '', }, { id: 4, dataCadastro: '2020-05-19T15:33:45.4807609+00:00', status: 1, description: '', } ]};

var result = Object.entries(obj).reduce((acc, [_, data])=>{
  data.forEach(elem=>{
     title = elem.dataCadastro.slice(0,10)
     acc[title] = acc[title] || {title, data:[]};
     acc[title].data.push(elem);
   });
 return acc;
},{});

console.log(Object.values(result));

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

Selenium Python option other than using send_keys()

I was looking to enhance the efficiency of this Python code and found a faster alternative: driver.get(myUrl) message = driver.find_element_by_id('message') send = driver.find_element_by_id('submit') for _ in range(myRange): messa ...

recurring issues with time outs when making ajax requests

During the development of my website, I tested it as localhost. Now that it's nearly complete, I switched to using my local IP address and noticed that about 30% of my ajax calls result in time out errors or 'failed to load resource errors'. ...

The parameter type 'Function' cannot be assigned to the parameter type 'ComponentType<never>'

Having an issue passing a component to the connect method from react-redux. The error message I'm receiving is as follows: Argument of type 'Function' is not assignable to parameter of type 'ComponentType'. Type 'Function&ap ...

Tools for diagnosing WebGL Three.js issues

Yesterday, I posed a question and now I want to take a different approach while still keeping the previous discussion going. (The initial question was about variable frame rates in Three.js.) Instead of directly addressing that question, I'm curious ...

Issue with Promise rejection not being caught in Node.js with ExpressNode.js and Express are not

Within my Express web application, I've created a function that outputs a Promise object. login: function(un, pass) { result = {}; var loginOk = new Promise( function (resolve, reject) { if (result.hasOwnPr ...

Adding elements to a JSON array in Javascript

Seeking assistance on updating a JSON array. var updatedData = { updatedValues: [{a:0,b:0}]}; updatedData.updatedValues.push({c:0}); This will result in: {updatedValues: [{a: 0, b: 0}, {c: 0}]} How can I modify the code so that "c" becomes part of ...

Identifying modifications to the content of a text area

Is there a way to determine if the value in my textareaId has changed due to JavaScript? For example: $("#buttonID").on("click, function(){ $("#textareaID").val("lorem ipsum"); }); $("#textareaID").change(function(){ //not working }); $ ...

Traversing through objects in react.js

Hello there, I'm currently learning React and JavaScript but facing some challenges with a particular task. Let's dive into it! So, imagine I have an array like this: clients = ["Alex", "Jimmy"] and then I proceed to create another array using th ...

The Bootstrap CDN is malfunctioning and displaying errors in the console

I attempted to incorporate Bootstrap 4.5 using the CDN provided on their main website. However, after adding all the code lines to my project, I encountered numerous issues with my custom CSS and the Bootstrap carousel failing to function. Upon inspecting, ...

Instructions on how to implement a readmore button for texts that exceed a specific character length

I am attempting to display a "Read more" button if the length of a comment exceeds 80 characters. This is how I am checking it: <tr repeat.for="m of comments"> <td if.bind="showLess">${m.comment.length < 80 ? m.comment : ...

Detailed steps on extracting values from an asynchronous function for individual elements of an array, followed by utilizing the retrieved values to display content in a JSX component within a React application

I am currently working on displaying information fetched from an API. While I can successfully fetch and display most of the data, there is a specific piece of information that requires an additional operation to be properly displayed. For each country, I ...

Utilizing AngularJS for Managing JSON Data

I'm facing a new challenge and need some assistance. My goal is to create 9 buttons and a panel that will display movie details based on the button clicked. For example, if I click 'Transformers', I want the panel to show details about Trans ...

What is the best way to send a request in a route and wait to return a response until the data is ready?

I've been advised to utilize axios for making API requests, but I'm encountering the issue of it being asynchronous and responding before the inner POST request is fully completed: var express = require('express'); const axios = require ...

Retrieving the value from a textbox within a Bootstrap modal in real-time

When displaying a table with user information and an option to edit details in a popup modal, the issue arises when trying to save changes. The textboxes in the modal always display the data from the first row of the table instead of the current user' ...

Using the onclick event with an image created through PHP code

I am currently in the process of developing a dynamic image represented as a graph displaying the number of documents generated each day. This interactive image is being created using PHP, and I aim to improve user engagement by enabling them to click on t ...

Receive alerts from flash document within html

I have a flash file embedded in an html document using the embed tag. I am looking for a way to trigger a JavaScript action, such as an alert, once the Flash content has finished playing. Is there a method to achieve this? ...

quiz stuck on last step due to xmhttp redirection problem

My learning project involves creating a PHP quiz with AJAX, which I am currently studying on Youtube. The goal is to have question number navigation displayed on the sidebar so that when a user clicks on any specific question number, the corresponding ques ...

Ensuring that undefined is not present before making an API request is crucial in the componentWillMount lifecycle

When I have a component that triggers methods depending on asynchronous API requests, I check certain props using componentWillmount. If a specific prop is true, I trigger a function; otherwise, I do not. The issue arises when the prop is initially undef ...

'Sys is not defined' JavaScript error

I've exhausted all my efforts searching for a solution online, but I'm still struggling to find an answer. I am facing a challenge with several projects that were initially developed for .Net 2.0 and hosted on IIS6 Server 2003 32 bit. Now, as pa ...

Locating the minimum position, arranging, and exchanging elements in a two-dimensional array using C++

Apologies for bringing up this query again, but I couldn't locate the answer due to differences in formatting and methods from what I have been learning. All functions need to be separate, and I haven't covered vectors or pointers yet. Some answe ...