Creating arrays that group timestamps into sets of three objects maximum per group, each group representing one day, can be achieved by

[Junior Dev !!] [Javascript] Hi !

How can I group timestamps into daily intervals with a maximum of 3 objects in each group?

I've seen examples of grouping by timestamp, but how do we both order and limit the array size at the same time?

I have:

const restuls= [
{date: "2022-10-14T21:14:41.000Z", id: "1"},
{date: "2022-10-14T21:15:48.000Z", id: "2"},
{date: "2022-09-20T18:16:01.000Z", id: "3"},
{date: "2022-09-20T18:16:48.000Z", id: "4"},
{date: "2022-09-20T21:14:52.000Z", id: "5"},
{date: "2022-09-20T21:14:15.000Z", id: "6"},
{date: "2022-09-20T21:14:03.000Z", id: "7"},
{date: "2022-09-18T10:09:33.000Z", id: "8"},
{date: "2022-09-18T10:08:12.000Z", id: "9"},
{date: "2022-09-18T10:07:50.000Z", id: "10"}
]

Expected output:

[
  [
   {date: "2022-10-14T21:14:41.000Z", id: "1"},
   {date: "2022-10-14T21:15:48.000Z", id: "2"}
  ],

  [
   {date: "2022-09-20T18:16:01.000Z", id: "3"},
   {date: "2022-09-20T18:16:48.000Z", id: "4"},
   {date: "2022-09-20T21:14:52.000Z", id: "5"}
  ],
  [
   {date: "2022-09-20T21:14:15.000Z", id: "6"},
   {date: "2022-09-20T21:14:03.000Z", id: "7"}
  ],
  [
   {date: "2022-09-18T10:09:33.000Z", id: "8"},
   {date: "2022-09-18T10:08:12.000Z", id: "9"},
   {date: "2022-09-18T10:07:50.000Z", id: "10"}
  ]
]

Thanks

Answer №1

Utilizing a simple function with modulo can efficiently solve the problem.

I quickly put together this code during work hours, but it may require some refactoring.

EDITED:

results = [{
    date: "2022-10-14T21:14:41.000Z",
    id: "1"
  },
  {
    date: "2022-10-14T21:15:48.000Z",
    id: "2"
  },
  {
    date: "2022-09-20T18:16:01.000Z",
    id: "3"
  },
  {
    date: "2022-09-20T18:16:48.000Z",
    id: "4"
  },
  {
    date: "2022-09-20T21:14:52.000Z",
    id: "5"
  },
  {
    date: "2022-09-20T21:14:15.000Z",
    id: "6"
  },
  {
    date: "2022-09-20T21:14:03.000Z",
    id: "7"
  },
  {
    date: "2022-09-18T10:09:33.000Z",
    id: "8"
  },
  {
    date: "2022-09-18T10:08:12.000Z",
    id: "9"
  },
  {
    date: "2022-09-18T10:07:50.000Z",
    id: "10"
  }
];

function groupByDateMaxThreeItems(array) {
  index = 0;
  arr = [];
  result = [];
  array = array.sort(function(a, b) {
    return new Date(b.date) - new Date(a.date);
  });

  for (item of array) {
    index = index + 1;
    if (index % 3 === 0 || !isSameDay(array[index - 1], item)) {
      result.push(arr);
      arr = [];
    }
    arr.push(item)
  }
  return result;
}

function isSameDay(item1, item2) {
  date1 = new Date(item1.date);
  date2 = new Date(item2.date);

  return (
    date1.getYear() + date1.getMonth() + date1.getDay() ==
    date2.getYear() + date2.getMonth() + date2.getDay()
  );
}

console.log(groupByDateMaxThreeItems(results));

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

Vue.js: Utilizing anonymous functions within props object

Looking to enhance the select2 example to make it more practical, I have added multiselect functionality and am now exploring custom select2 configuration options. Check out my progress on jsFiddle Encountering an issue where function properties of props ...

Is there a way to retrieve JSON data with form.submit()?

Greetings, I have successfully submitted a form from jQuery using the following code: $('#form').submit(); The form is successfully submitted to the server. However, I am looking to return JSON data from the post request so that I can dynami ...

After updating to Angular 7, an error was encountered: "TypeError: Unable to execute map function on ctorParameters"

After updating my Angular project to version 7, I encountered a new issue. When running "ng serve --open" from the CLI, I received the following error message: Uncaught TypeError: ctorParameters.map is not a function at ReflectionCapabilities._own ...

Tips for transferring backend information to show up as options in a multiselect dropdown menu (Jsfiddle link included)

Here is a reference to a fiddle link -->> https://jsfiddle.net/etfLssg4/ In the fiddle, users can select multiple dropdown items. The dropdown values are initialized with Lisa and Danny as the default items. These default selections are displayed in ...

Execute a join operation on a dataset solely based on the matching of substrings

Looking to perform a join on a collection where student names match and the last string after the "_" in the log column's value matches the id variable. The challenge lies in matching a substring of a string within the logs column. One way to achieve ...

extract() of the incoming information

I'm currently tackling a project in Angular that involves user input into an input field. The task is to truncate the text at 27 characters and add "..." at the end if it exceeds that limit. I've attempted to achieve this using the slice() method ...

The Everyday Explanation of Same Origin Policy

Could anyone simplify the concept of the Same Origin Policy for me? I've come across various explanations but I'm in search of one that a child can easily understand. I found this link to be quite helpful. Is there anyone who can provide further ...

Can you update the `runtime` property to `segment` in the export config?

I'm currently working on setting up an upload API route within my application. /admin/upload However, when I attempt to console.log(req.file), it returns as undefined. This seems to be related to the following configuration: export const config = { ...

When comparing TypeScript class functions with regular functions and variables, which one yields better performance?

When it comes to defining functions, is it better to use variables or functions directly? Also, how does this affect tree-shaking? I am dealing with a lot of calculation-intensive helper classes and I am unsure about the optimal approach in terms of memor ...

I encountered a 404 error when attempting to execute the "npm publish" command

While attempting to publish a package to the npm registry, an error is encountered after running the command npm publish. npm WARN prepublish-on-install As of npm@5, `prepublish` scripts are deprecated. npm WARN prepublish-on-install Use `prepare` for buil ...

Encountering difficulty retrieving data upon initial click within an Android webview during server communication

I have encountered an issue when calling this method from JavaScript. The data is returning as null for the first time, but starting from the second time it works fine. Seeking assistance on this matter. @SuppressLint("JavascriptInterface") public Str ...

Ways to add AJAX information to select2

I am currently utilizing a select2 dropdown feature and I am attempting to configure it in such a way that it dynamically displays the leads based on the JSON response. As you can observe in the image provided below, the text correctly yields a JSON array ...

Implementing ui-sref-active for intricate routing states

I have implemented the menu link using AngularJS and UI-Router. <li ui-sref-active="active"> <a ui-sref="dashboard" title="Dashboard"><i class="fa fa-lg fa-fw fa-home"></i> <span class="menu-item-parent">Dashboard</spa ...

Running npm start in a React development environment on Linux without automatically opening a browser can be achieved by configuring

As I dive into learning React, I've noticed that I keep running npm start in the terminal multiple times. However, it can be quite frustrating how a new browser window opens each time. I'm currently attempting to prevent this from occurring on my ...

Extract data from a website with Python and selenium

I need to scrape the data from a table that seems to be generated in JavaScript. I'm using selenium and Python3 for this task. While looking at how others have approached similar challenges, I noticed they use xpath to locate the tables before scrapin ...

Issue with data-ng-class function not being invoked

I'm currently working on a simple Angular project where I need to dynamically color list items based on a function called in data-ng-class. Below is an excerpt from my HTML file: <div> Rooms:<ul style="list-style:none;"> < ...

Sending the object context back to the controller callback from an AngularJS Directive

I am currently working on creating a modified version of ng-change with a delay feature for auto-saving changes. Here is the custom directive I have implemented: myApp.directive('changeDelay', ['$timeout', function ($timeout) { re ...

The use of the 'v-on' directive with the 'KeyboardEvent.keyCode' modifier is no longer recommended in Vue. It is now recommended to use 'KeyboardEvent.key' instead

I am currently in the process of upgrading my Vue 2 application to Vue 3. However, when I run the application, I encounter some deprecation errors. Previously, I used numbers and "key" in my keyboard event modifiers. This approach is now deprecated in Vue ...

What is the most effective way to modify a specific field within a MongoDB document - utilizing either the update or patch hook in FeathersJS?

I am currently working on updating a single field in a MongoDB document, and I am unsure whether to use the patch or update method within the Feathers framework. Can someone provide an example of how to do this? const { authenticate } = require('feat ...

Issue encountered while fetching data from SQL database in a Node.js application

After successfully connecting the database to my node js project, I encountered an issue when attempting to retrieve data using the get operation. Despite the connection working fine, I was unable to resolve the error that occurred. Establishing the SQL c ...