Is there a way to find the minimum and maximum intervals based on a consecutive property in a JavaScript Object?

Seeking assistance in calculating the maximum and minimum date differences (in hours or float days) for each location. When there is only one date interval for a location, consider the difference from the date above it. The data is already sorted by date (descending) and the rack is consistent across all entries, thus can be ignored. Thank you.


var data = [
    {rack: 1208, location: 42, date: "2020-05-11T13:53:51.000Z"},
    {rack: 1208, location: 42, date: "2020-05-08T12:36:51.000Z"},
    {rack: 1208, location: 40, date: "2020-05-08T12:36:27.000Z"},
    {rack: 1208, location: 41, date: "2020-05-08T10:44:40.000Z"},
    {rack: 1208, location: 41, date: "2020-05-08T10:43:33.000Z"},
    {rack: 1208, location: 42, date: "2020-05-08T10:42:55.000Z"},
    {rack: 1208, location: 41, date: "2020-05-08T10:41:55.000Z"},
    {rack: 1208, location: 40, date: "2020-05-08T10:41:18.000Z"},
    {rack: 1208, location: 40, date: "2020-05-08T09:47:42.000Z"},
    {rack: 1208, location: 40, date: "2020-05-07T10:24:56.000Z"}
]

var response = {
   42: {
       minHours : {
           value: 0.01,
         startTime: '2020-05-08T10:42:55.000Z',
         endTime: '2020-05-08T10:43:33.000Z'
       },
       maxHours : {
           value: 73.28,
         startTime: '2020-05-08T12:36:51.000Z',
         endTime: 'NOW() Current Datetime'
       }
  },
  41: {
       //do the same
  },
  40: {
       //do the same
  }
};

This concept is akin to a timeline where tracking the "rack" movement is necessary.

1) Starting from the bottom up: the rack arrived at site 40 on 2020-05-07T10:24:56.000Z before moving to site 41 on 2020-05-08T10:41:55.000Z. Therefore, the rack spent 24.28 at location 40.

2) Subsequently, the rack reached site 41 on 2020-05-08T10:41:55.000Z followed by its move to site 42 at 2020-05-08T10:42:55.000Z. Hence, the duration of stay at site 41 was 1 minute or 0.016 hours.

The process continues with each comparison updating the maxHours and minHours for that location based on whether the difference exceeds the current maxHours or falls below minHours.

Answer №1

What a fascinating challenge this was! After analyzing your data, I realized that subsequent entries for a location were redundant, so I opted to filter them out, simplifying the problem significantly. The script runs through the list of entries and compares the time of the next entry (which inherently indicates a change in location) with the current one, updating the result object accordingly. I hope this explanation clarifies things!

const data = [
  { rack: 1208, location: 42, date: "2020-05-11T13:53:51.000Z" },
  { rack: 1208, location: 42, date: "2020-05-08T12:36:51.000Z" },
  { rack: 1208, location: 40, date: "2020-05-08T12:36:27.000Z" },
  { rack: 1208, location: 41, date: "2020-05-08T10:44:40.000Z" },
  { rack: 1208, location: 41, date: "2020-05-08T10:43:33.000Z" },
  { rack: 1208, location: 42, date: "2020-05-08T10:42:55.000Z" },
  { rack: 1208, location: 41, date: "2020-05-08T10:41:55.000Z" },
  { rack: 1208, location: 40, date: "2020-05-08T10:41:18.000Z" },
  { rack: 1208, location: 40, date: "2020-05-08T09:47:42.000Z" },
  { rack: 1208, location: 40, date: "2020-05-07T10:24:56.000Z" },
];

const getTimes = (data) => {
  // Make a shallow copy to avoid mutating the original input
  const dataCopy = [...data];
  // Remove duplicate location records and reverse the array for chronological order
  const filteredData = dataCopy.reverse().filter((item, idx) => {
    if (idx === 0) {
      return true;
    }
    return item.location !== data[idx - 1].location;
  });
  let result = {};

  filteredData.forEach((item, idx) => {
    if (!result[item.location]) {
      result[item.location] = {
        minHours: { value: Number.MAX_VALUE, startTime: item.date },
        maxHours: { value: Number.MIN_VALUE, startTime: item.date },
      };
    }

    const nextLocationData = filteredData[idx + 1];
    const currentTime = new Date();
    const nextTime = nextLocationData ? Date.parse(nextLocationData.date) : currentTime.getTime();
    let timeDiff = (nextTime - Date.parse(item.date)) / 36e5;

    if (timeDiff > result[item.location].maxHours.value) {
      result[item.location].maxHours = {
        value: timeDiff,
        startTime: item.date,
        endTime: nextLocationData ? nextLocationData.date : currentTime.toISOString(),
      };
    }

    if (timeDiff < result[item.location].minHours.value) {
      result[item.location].minHours = {
        value: timeDiff,
        startTime: item.date,
        endTime: nextLocationData ? nextLocationData.date : currentTime.toISOString(),
      };
    }
  });

  return result;
};

console.log(getTimes(data));

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 is preventing d3.json from including cookies in the request?

I'm delving into the world of ajax requests with d3.js (v5) and I'm facing a little hiccup. Here's my code snippet: d3.json(uri).then(data =>console.log(data)); When I tried this in an app utilizing cookie authentication, I consistently ...

Exploring CountUp functionality with Vue framework

I'm still getting the hang of Vue and recently completed my first project following a tutorial. This project is my first solo endeavor. Currently, I am working on a basic page to display the scores between two teams. The scores are retrieved from an ...

Angular 8 project experiencing issues with Bootstrap dropdown functionality

I have successfully installed the packages listed below: npm install --save bootstrap@3 npm install --save popper.js angular-popper npm install jquery --save Afterwards, I included the styles and scripts in the angular.json file in the exact order as sho ...

Is it possible to duplicate a div element and then make changes to both the original and the clone using a single button

I am dealing with an element that has three sub-elements element1, element2, and element3. When I press the button1 command, it filters element1. When I press the button2 command, it filters element2. How can I clone this element and manipulate both th ...

I am experiencing issues with the ng-dropdown-multiselect library and it is not functioning

Check out this awesome library for creating dropdown menus using angularjs and twitter-bootstrap-3 at: . I am trying to implement the examples provided. In my html, I have: <div ng-dropdown-multiselect="" options="stringData" selected-model="stringMod ...

Steps for transforming an array of file names into JSON format and including a specific key

I am in the process of creating a new website that will display all the files contained in a specific folder. However, I am facing an issue with converting an array of document names into JSON format. In order to achieve this, I understand that I need to ...

Can you help understand the unexpected output produced by this JavaScript code?

When looking at the following JavaScript code, you would expect an output of 32. However, the actual answer is 16. How is this possible? 5 + 1 = 6; 6 + 5 = 11; 11 * 2 = 22; 22 + 10 = 32; (this should have been the correct answer) var x = 5; x = (x++, a ...

Could this be a substance made of pure white energy?

It appears that the default color for SpriteMaterial is 0xFFFFFF, which indicates no color. However, if I change the color property of the material to say 0xFF0000, the sprite will display a red tint. If I desire a white tint instead, how can this be achi ...

Verify optional chaining support in Angular app for browsers

Within my Angular application, I am looking to verify if a client's browser supports optional chaining (es2020) in order to load a library that contains both a modern ES version and a legacy one. The issue arises when the Angular compiler (which I su ...

Unable to locate object for property 'setAttribute' and thus it is undefined

I am attempting to create an accordion using the code below. It works perfectly when the tags are placed together. However, I wish to insert an element inside a different tag elsewhere on the page. <dt> <li class="nav-item" i ...

AJAX requests sent from different origins to AWS S3 may encounter CORS errors on occasion

My current objective is to access publicly available files stored in S3. The CORS configuration for my S3 setup is as follows: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> < ...

Preventing users from using alt+tab on an IE8 aspx web page

I need help with disabling the alt+tab function in my IE8 web browser for a page that displays a modal dialogue. Can anyone assist me with this issue? ...

Issue with deploying Azure node.js application due to libxmljs error

My goal is to launch my website using libsmljs built on node.js on Windows Azure. However, during the deployment process on Azure, I encounter a failure with the following error message: Command: C:\DWASFiles\Sites\CircuitsExpress\Virt ...

Oops! RangeError [MESSAGE_CONTENT_TYPE]: The content of the message must be a string that contains at least one character

Can someone help me troubleshoot my regular send command? I keep encountering an error message even after following suggestions from previous answers. Here is the error: RangeError [MESSAGE_CONTENT_TYPE]: Message content must be a non-empty string. at ...

Learn the steps to create a 3D carousel that spins on its own without the need for manual clicks and pauses once the

Looking for a solution to create a 3D carousel that rotates continuously without the need for buttons to be clicked, and pauses when the mouse hovers over it, then resumes rotation when the mouse is not hovering over it. var carousel = $(".carousel"), ...

What would be the most effective approach for creating a reactive setter for an object within an array in Vuex?

I am working with a Vuex object that contains an array of languages consisting of objects with guid, name, and level properties. I am trying to figure out how to write a method that will make it reactive. Currently, I have an input field with a value of " ...

Choose several locations recommended by Google Places

Looking to implement a multiple select feature on v-select to allow users to select one or more cities suggested by Google. Has anyone successfully done this before? I haven't been able to find any examples. https://vue-select.org/ ...

Building the logic context using NodeJS, SocketIO, and Express for development

Exploring the world of Express and SocketIO has been quite an eye-opener for me. It's surprising how most examples you come across simply involve transmitting a "Hello" directly from app.js. However, reality is far more complex than that. I've hi ...

The Foundation 6 Zurb Template is not compatible for offline use

After successfully installing Foundation 6 Zurb Template via the cli, I encountered no issues. I then added the missing babel install and everything worked fine online. However, BrowserSync does not seem to work offline. Upon initiating watch, I receive a ...

Utilizing recursive methods for discovering routes in a two-dimensional matrix

Currently in the process of my A-level project, I am focused on the task of determining the maximum flow of a network using javascript. My approach involves working with a 2D array where the values in the array represent distances between two points. For ...