Converting an array of objects in JavaScript to a categorized array based on dates

I have an array of objects containing dates and I need to categorize them based on specific date categories.

const orders = [
  {
    "order_id": "1",
    "description": "Description 1",
    "date": "2024-02-03T19:00:57.744Z",
  },
  {
    "order_id": "2",
    "description": "Description 2",
    "date": "2024-02-04T19:00:57.744Z",
  },
  {
    "order_id": "3",
    "description": "Description 3",
    "date": "2024-02-06T19:00:57.744Z",
  },
]

In addition, there are predefined date categories:

const category = [
  'Overdue',
  'Today',
  'Tomorrow',
  'This Week',
  'Next Week',
  'This Month',
  'Next Month',
  'Later',
  'No Date',
];

The goal is to create a new array with sorted data based on the specified date categories.

Expected output:

[
  {
    "category": "Today",
    "data": [
      {
        "order_id": "1",
        "description": "Description 1",
        "date": "2024-02-03T19:00:57.744Z"
      }
    ]
  },
  {
    "category": "Tomorrow",
    "data": [
      {
        "order_id": "2",
        "description": "Description 2",
        "date": "2024-02-04T19:00:57.744Z"
      }
    ]
  },
  {
    "category": "This Week",
    "data": [
      {
        "order_id": "3",
        "description": "Description 3",
        "date": "2024-02-06T19:00:57.744Z"
      }
    ]
  }
]

A custom function using dayjs library is used to determine the appropriate category for each date.

const getCategoryByDate = date => {

    // Function logic goes here

};

To transform the original array into the desired format, Array.reduce method is utilized.

const output = orders.reduce((acc, curr) => {

    // Transformation logic goes here

}, []);

However, it's important to note that the output array might not be in the correct order if the original orders array is not pre-sorted by date.

Answer №1

To optimize your code, consider transforming your categories into an object containing dates represented as strings using dayjs or vanilla JavaScript. Then, utilize the Array::findLast() method to search for a specific category efficiently.

This approach is more efficient than repeatedly calling date functions during comparisons.

If your dates are not in order, make sure to sort them based on the index keys of the categories after the transformation.

const orders = [
  {
    "order_id": "1",
    "description": "Description 1",
    "date": "2024-02-03T19:00:57.744Z",
  },
  {
    "order_id": "2",
    "description": "Description 2",
    "date": "2024-02-04T19:00:57.744Z",
  },
  {
    "order_id": "3",
    "description": "Description 3",
    "date": "2024-02-06T19:00:57.744Z",
  },
];

// dynamically generate
const categories = {
  Today: '2024-02-03',
  Tomorrow: '2024-02-04',
  'This week': '2024-02-05',
  // add more entries
};

const result = orders.reduce(((map, categories) => (r, item) => {
  if(!item.date){
    // add to no date category
    return r;
  }
  const cat = categories.findLast(([title, date]) => date < item.date);
  if(!cat){
    // add to overdue category
    return r;
  }
  (map[cat[0]] ??= r[r.length] = {category: cat[0], data: []}).data.push(item);
  return r;
  
})({}, Object.entries(categories)), []);

console.log(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

Is it possible to expand the Angular Material Data Table Header Row to align with the width of the row content?

Issue with Angular Material Data Table Layout Link to relevant feature request on GitHub On this StackBlitz demo, the issue of rows bleeding through the header when scrolling to the right and the row lines not expanding past viewport width is evident. Ho ...

Trouble with Ajax program loading properly in Chrome browser

I have developed a small ajax program and encountered an issue. While it works perfectly fine on Internet Explorer 11, it does not function correctly on Chrome and Firefox. Here is the HTML file snippet: <html> <head><title>Ajax Page< ...

Attempting to render an image onto a canvas and apply Caman.js for image editing purposes

Currently, I have a code snippet that allows me to draw an image onto a canvas. Here is the code: var imageLoader = document.getElementById('imageLoader'); imageLoader.addEventListener('change', handleImage, false); var ...

Pattern matching excluding content contained within specific bbcode markup is known as regex

Looking to convert double quotes to curly quotes, but excluding certain tags like [quote] and [code]. Example Input [quote="Name"][b]Alice[/b] said, "Hello world!"[/quote] <p>"Why no goodbye?" replied [b]Bob[/b]. "It's always Hello!"</p> ...

"Enhance your website with captivating Javascript hover effects for

Can anyone assist me with incorporating the navigation hover effect seen on this website into my HTML/CSS project? The example site is built using a WordPress theme, but I am looking to apply that green effect to my own webpage and have the ability to cust ...

What is the best way to arrange elements based on the numeric value of a data attribute?

Is there a way to arrange elements with the attribute data-percentage in ascending order, with the lowest value first, using JavaScript or jQuery? HTML: <div class="testWrapper"> <div class="test" data-percentage="30&qu ...

Storing tokens using the strtok function in a pointer within an array

There are still some lingering issues that I need to resolve, but once I tackle this one, everything should fall into place. The challenge is parsing a line using the strtok function with space as the delimiter. My goal is to store all the tokens in an ar ...

Freeing up memory for an array allocated to a pointer member variable

As I delve into this textbook, it mentions the necessity of including code in the destructor to deallocate memory when a member variable is a pointer. This concept is somewhat vague, but according to the text, it should look something like this: private: ...

Managing jquery values with cookies for loading, saving, and resetting

I recently implemented screen adjustments on my website using scrollbars. I utilized this example as a reference. Below is the code snippet... HTML CODE: <h1>Image Editor with CSS Filters and jQuery</h1> <!--Form for collecting image URL ...

The error message "global.HermesInternal - Property 'HermesInternal' is not found in the type 'Global & typeof globalThis'" appeared

I ran the auto-generated code below: $ react-native init RepeatAloud App.tsx /** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local * ...

What could be causing my if-else statement to malfunction in JavaScript?

I'm working on a form where certain conditions need to be met based on the selected order type. For instance, if a market order is chosen, the stop price and limit price should default to zero and become read-only fields. Similarly, selecting a limit ...

What is the correct way to utilize a variable as a parameter in React Query while employing the axios.request(options) method?

I'm currently working on a React Query component with the following structure: function test () { const [var, setVar] = useState("") const options = { method: "GET", url: "https://api.themoviedb.org/3/search/tv" ...

Achieving a bookshelf model by combining data from several tables simultaneously

In the process of creating a node.js web service with the functionality of an auction, I am utilizing bookshelf.js for models and MySQL for the database. The database structure to consider is as follows: users: id | login | password | ...

Organizing a PHP entity

I have a PHP object that has the following output: Array ( [0] => stdClass Object ( [id] => 25 [itemid] => 13 [studentid] => 9 [score] => 22 [imagealt] => ...

Tips for iterating through a JSON object in JavaScript and building a table from it

My JSON data is structured like this: diferencias = { "1": { "1": 543.0, "0": 542.0 }, "2": { "0 1": 0.3333333333333333 } } I am trying to create a table with the outer keys as columns. This is the code I have written ...

What is the best way to trigger ajax when the user clicks the back button to return to the previous webpage?

Check out my code snippet below: HTML Code <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="body"> <div class="dropdown_div"> <select id="q_type" class="dropdown" ...

What is the best way to create a new row within a Bootstrap table?

Struggling to format an array inside a table with the `.join()` method. The goal is to have each car on a separate row. Attempts using `.join("\r\n")` and `.join("<br />")` have been unsuccessful. What am I overlooking? ...

When attempting to run HTML and JavaScript files locally, an error is encountered: "TypeError: The module name 'openai' is not resolving to a valid URL."

As a beginner in web development, I decided to follow a tutorial on creating a web application using the OpenAI API. The tutorial instructor runs the code in an environment called Scrimba, but I am working on my MacBook. This is how the app functions: it ...

Issue: The automation server is unable to generate the object

I am encountering an issue with the code snippet below, which is causing an error specifically in the IE-11 web browser: var excApp = new ActiveXObject("Excel.Application"); The error message being displayed is: Error: Automation server can't create ...

Issue encountered when attempting to modify the directive when the drop-down list is changed in AngularJS

Experiencing issues updating the directive when the drop down list is changed using AngularJS. Below is my application code: HTML Code <div ng-app="myApp" ng-controller="MyCtrl"> <select ng-model="opt" ng-options="font.title for font in font ...