Divide a collection of objects into groups based on 2-hour time spans

I have an array of objects that I need to split into chunks of 2 hours each, starting on the hour (e.g. 10.00 - 12.00, 12.00 - 14.00, etc).

Here is my current solution, but I feel like it may not be the most efficient:

Please consider the day variable, which is defined as moment().startOf('day')

I'm open to a Lodash approach if anyone has one.

Example data:

// array of objects with eventStart timestamps

Expected output:

// chunks of data split into 2-hour intervals

Here is a simplified version of the code for the question:

// code snippet
// JavaScript code

Answer №1

To achieve the desired result, you can utilize lodash's _.groupBy() function. The key can be generated by creating a date from the eventStart value, rounding it down to the nearest even hour (start), and then returning a range of start to start + 2:

const data = [{"data":42986084,"eventStart":1575621000000},
{"data":43729858,"eventStart":1575626400000},{"data":43727728,"eventStart":1575627000000}];

const result = _.groupBy(data, o => {
  const hour = new Date(o.eventStart).getHours(); // obtain the hour
  const start = hour - hour % 2; // normalize to the closest even hour
  
  return `${start}-${start + 2}`; // generate the key
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

The same concept can be applied using Array.reduce():

const data = [{"data":42986084,"eventStart":1575621000000},
{"data":43729858,"eventStart":1575626400000},{"data":43727728,"eventStart":1575627000000}];

const createRangeKey = eventStart => {
  const hour = new Date(eventStart).getHours(); // obtain the hour 
  const start = hour - hour % 2; // normalize to the closest even hour
  
  return `${start}-${start + 2}`; // generate the key
};

const result = data.reduce((r, o) => {
  const key = createRangeKey(o.eventStart); // obtain the key
  
  if(!r[key]) r[key] = []; // initialize if not present in the object
  
  r[key].push(o); // add the object to the key
  
  return r;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

If you want to exclude hours outside the 8-24 range, you can check if the start value is less than 8. For example, the entry

{"data":"ignore","eventStart": 1575669600000}
would be disregarded in this case.

const data = [{"data":42986084,"eventStart":1575621000000},
{"data":43729858,"eventStart":1575626400000},{"data":43727728,"eventStart":1575627000000}, {"data":"ignore","eventStart": 1575669600000}];

const result = data.reduce((r, o) => {
  const hour = new Date(o.eventStart).getHours(); // obtain the hour
  
  const start = hour - hour % 2; // normalize to the closest even hour
  
  if(start < 8) return r;
  
  const key = `${start}-${start + 2}`; // generate the key
  
  if(!r[key]) r[key] = []; // initialize if not present in the object
  
  r[key].push(o); // add the object to the key
  
  return r;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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 include a visible comment in an ajax call that can be viewed in Fiddler when analyzing the outgoing data?

Here is an example of the code I am working with: $.ajax({ cache: false, url: "/xx" }).done(onAjaxDone).fail(function (jqXHR, textStatus, errorThrown) { Dialog.Alerts.ajaxOnFailure(jqXHR, textStatus, err ...

Having trouble understanding why my submission button isn't working

I'm struggling to understand why my submit button isn't working correctly. Initially, I had an e.preventDefault() at the beginning and it didn't have any effect. However, after receiving advice from an instructor, I included it in the condit ...

Checking a bcrypt-encrypted password in an Express application

I am encountering an issue with my login password verification code. Even when the correct password is entered, it is not being validated properly. Can anyone provide assistance with this problem? login(req, res) { const { email, pass } = req.body; ...

Retrieve worldwide data for the entire application in Next.js during the first page load

Within my Next.js application, I am implementing search filters that consist of checkboxes. To display these checkboxes, I need to retrieve all possible options from the API. Since these filters are utilized on multiple pages, it is important to fetch the ...

Refresh your webpage with new content and modified URLs without the need to reload using window.history.pushState

Hey everyone, I'm looking to incorporate window.history.pushState into my website, but I'm unsure of how to go about it... What I'm aiming for is to have a page dashboard.php and update the URL to dashboard.php?do=edit&who=me, while loa ...

Utilizing React and MobX to dynamically render components based on observable arrays

I'm currently facing a challenge with trying to map an array in order to display components for each entry. Here's my current approach: Here is the structure of my RankStore; const RankStore = observable({ loading: false, error: "", ra ...

Tips for displaying NoOptionsText in MaterialUI Autocomplete based on a specific condition

When using a Material UI autocomplete feature, the items are selected based on the first 3 letters typed. For example, if you're searching for all "Pedros" in your database, typing "Ped" will bring up results starting with those letters. The issue ar ...

Displaying images retrieved from firebase on a React.js application

Currently, I am attempting to retrieve images from Firebase storage and then exhibit them in a React component. As a newcomer to React/Javascript, I find it challenging to grasp the asynchronous nature of React/JS. The issue I'm facing is that althoug ...

New item isn't successfully appended to the associative array

Within my code, I am iterating through an array named projects. Each project within this array is represented as an associative array. My goal is to extract the image properties and then append a new element containing these properties to each individual p ...

Navigating different domains in ExpressJS - Handling CORS

Currently, I am facing a challenge in setting the domain for a cookie that I am sending along with the response from my ExpressJS implementation. Unfortunately, at the moment, it is only being set to the IP address of where my ExpressJS server is located. ...

Angular - connecting a function directly

Is there any potential performance impact of directly binding a function in directives like ng-show in AngularJS? <div ng-show="myVm.isVisible()"> .... </div> // controller snippet (exposed through controllerAs syntax) function myCtrl (myServ ...

How can an object inside an array be destructured in just one line?

Consider the following array: const array = [{b:2}] Can you extract the value of b using destructuring in just one line? I attempted something similar to this approach, but it did not yield the desired result: const [{b} = array] ...

Is it considered poor form to send as many as 100 ajax requests when loading a webpage?

My table can display up to 100 rows, sometimes even more. Is it considered a bad practice to loop through all these rows and send an AJAX post request to fetch data? I am hesitant to do this during the page load as it may significantly slow down the loadin ...

Exploring the world of Ajax with jQuery

Could someone help me figure out how to integrate Ajax into my PHP code so that the content can load dynamically? Currently, it looks something like this: First, a user selects a category: <li><a href='?genre=sport'>Sport</a>& ...

Creating element modules in EJS

After building experience with React, I am now faced with the task of using ejs in my current project. Specifically, I need to return multiple radio elements. My attempt at achieving this was through the following code: <% const renderRadios = (value, ...

Invoking an asynchronous method of the superclass from within an asynchronous method in the subclass

I'm currently developing JavaScript code using ECMAScript 6 and I'm facing an issue with calling an asynchronous method from a superclass within a method of an extending class. Here is the scenario I'm dealing with: class SuperClass { c ...

Exploring the Fusion of Material UI Searchbox and Autocomplete in React

Looking for help with my AppBar component from Material UI. I want the Searchbox field to function similarly to what is seen on https://material-ui.com/. It should appear as a Searchbox but display selectable options like Autocomplete after entering input. ...

Is it possible to determine the time format preference of the user's device in Angular? For example, whether they use a 24-hour system or a 12-hour system with AM

In Angular, is there a way to determine whether the user's time format is set to 24-hour or 12-hour system? Any help would be greatly appreciated. Thanks! ...

New methods for Sequelize ES6 models do not currently exist

Encountering issues while using Sequelize JS v4 with ES6 classes, I'm facing difficulty with the execution of instance methods. Despite being defined in the code, these methods appear to be non-existent. For instance - Model File 'use strict&a ...

Using Jquery to select a specific id for an input element that is a checkbox

I've been working on a snippet of jQuery code that I'd like to tailor to be more specific for one of two different input elements on my HTML page. <script> // ensure only one box is checked at a time $(document).ready(function() { ...