Utilizing Array.reduce to Compute Time Discrepancy

Utilizing the array.reduce method, this code calculates the time differences between start and stop as it traverses through the array.

However, this basic implementation does not factor in events or tasks, for instance.

let data = [
  {
    action: "start",
    time: 100
  },
  {
    action: "stop",
    time: 150
  }, 
  {
    action: "start",
    time: 250
  }, 
  {
    action: "stop",
    time: 350
  }, 
  {
    action: "start",
    time: 400
  }
];

let end = 450; // should be Date.now(),

let sum = data.reduce(function (r, a) {

  return r + (a.action === 'start' ? -a.time : a.time);

}, data[data.length - 1].action === 'start' ? end : 0);

console.log(sum);

A potential scalable version of the data array could look like this:

let data = [
  {
    activity: "JOB",
    event: "CLOCK IN",
    task: "TRAVEL",
    desc: "Job #12345",
    time: 100
  },
  {
    activity: "JOB",
    event: "CLOCK IN",
    task: "ON SITE",
    desc: "Job #12345",
    time: 150
  }, 
  {
    activity: "JOB",
    event: "CLOCK IN",
    task: "BREAK",
    desc: "Job #12345",
    time: 250
  }, 
  {
    activity: "JOB",
    event: "CLOCK IN",
    task: "ON SITE",
    desc: "Job #12345",
    time: 350
  }, 
  {
    activity: "JOB",
    event: "CLOCK OUT",
    task: "HOME",
    desc: "Job #12345",
    time: 450
  }
];

The process of learning Array.reduce has posed some challenges. Any guidance on how to approach it would be highly appreciated.

What modifications can be made to iterate through a scalable array using this code?

Answer №1

If there will be a sequence of CLOCK IN and CLOCK OUT events for multiple jobs in your data, consider the following example:

const schedule = [
  {
    activity: "JOB",
    event: "CLOCK IN",
    task: "TRAVEL",
    description: "Job #1",
    time: 100
  },
  {
    activity: "JOB",
    event: "CLOCK OUT",
    task: "ON SITE",
    description: "Job #1",
    time: 150
  }, 
  {
    activity: "JOB",
    event: "CLOCK IN",
    task: "BREAK",
    description: "Job #2",
    time: 250
  }, 
  {
    activity: "JOB",
    event: "CLOCK OUT",
    task: "ON SITE",
    description: "Job #2",
    time: 350
  }, 
  {
    activity: "JOB",
    event: "CLOCK IN",
    task: "HOME",
    description: "Job #3",
    time: 450
  },
  {
    activity: "JOB",
    event: "CLOCK OUT",
    task: "HOME",
    description: "Job #3",
    time: 500
  }
];

The above snapshot displays the CLOCK IN and CLOCK OUT events for three distinct jobs: Job #1, Job #2, and Job #3.

If you believe this is correct, then the subsequent code snippet should offer the desired outcome:

const jobSchedule = schedule.reduce((prev,event)=>({
  ...prev,
  [event.description]:{
    ...prev[event.description],
    [event.event]:event.time
  }
}),{})

This transforms the data into an object structured like this:

{
  'Job #1': { 'CLOCK IN': 100, 'CLOCK OUT': 150 },
  'Job #2': { 'CLOCK IN': 250, 'CLOCK OUT': 350 },
  'Job #3': { 'CLOCK IN': 450, 'CLOCK OUT': 500 }
}

We can further enhance each job item within that object by calculating the duration using the method below:

const updatedResult = Object.entries(jobSchedule).reduce((prev,entry)=>{
  const [key,value] = entry
  return ({
    ...prev,
    [key]:{
      ...value,
      DURATION: value['CLOCK OUT'] - value['CLOCK IN']
    }
  })
}
,{})

The result is as follows:

{
  'Job #1': {
    'CLOCK IN': 100,
    'CLOCK OUT': 150,
    DURATION: 50
  },
  'Job #2': {
    'CLOCK IN': 250,
    'CLOCK OUT': 350,
    DURATION: 100
  },
  'Job #3': {
    'CLOCK IN': 450,
    'CLOCK OUT': 500,
    DURATION: 50
  }
}

How does that appear to you?

See the functional example below:

const schedule = [
  {
    activity: "JOB",
    event: "CLOCK IN",
    task: "TRAVEL",
    description: "Job #1",
    time: 100
  },
  {
    activity: "JOB",
    event: "CLOCK OUT",
    task: "ON SITE",
    description: "Job #1",
    time: 150
  }, 
  {
    activity: "JOB",
    event: "CLOCK IN",
    task: "BREAK",
    description: "Job #2",
    time: 250
  }, 
  {
    activity: "JOB",
    event: "CLOCK OUT",
    task: "ON SITE",
    description: "Job #2",
    time: 350
  }, 
  {
    activity: "JOB",
    event: "CLOCK IN",
    task: "HOME",
    description: "Job #3",
    time: 450
  },
  {
    activity: "JOB",
    event: "CLOCK OUT",
    task: "HOME",
    description: "Job #3",
    time: 500
  }
];

const jobSchedule = schedule.reduce((prev,event)=>({
  ...prev,
  [event.description]:{
    ...prev[event.description],
    [event.event]:event.time
  }
}),{});

const updatedResult = Object.entries(jobSchedule).reduce((prev,entry)=>{
  const [key,value] = entry
  return ({
    ...prev,
    [key]:{
      ...value,
      DURATION: value['CLOCK OUT'] - value['CLOCK IN']
    }
  })
}
,{});

console.log(updatedResult);

Answer №2

In order to meet your requirements, it seems like you will need two distinct functions called isStartType() and isStopType(). These functions can utilize a simple switch case structure to return the desired value. Alternatively, if you are confident that unexpected types will not be received, you could potentially make do with just a single function like isStartType(). In this scenario, you would then need to adjust the line from a.action === 'start' to instead read isStartType(a['propertyName']).

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

The primary Android thread is obstructing the WebView thread

Recently, I've been tackling an issue involving making a synchronous call to JavaScript within a WebView, with the aim of retrieving a return value. However, pinpointing why this setup is not functioning properly has proven to be quite challenging for ...

The useEffect function is not being executed

Seeking assistance from anyone willing to help. Thank you in advance. While working on a project, I encountered an issue. My useEffect function is not being called as expected. Despite trying different dependencies, I have been unable to resolve the issue ...

Making Monaco compatible with the integration of Vuejs and electron

I am intrigued by the idea of integrating the Monaco editor into a Vue.js backed Electron project. So far, I have successfully run Microsoft's Electron sample for the Monaco editor. There are several npm repositories for vue.js and monaco, but none o ...

Tips for incorporating setState with a nested JSON array object

Is there a way I can update the bookInstances data in MongoDb using setState? I want to use setState to update bookInstances, with each array formatted like {"id": ...} export default class BookInstances extends Component { constructor(props) { ...

Steps for implementing form loading with ajax

I am in the process of creating a straightforward login and registration form using ajax. The code I have written is as follows: function loadRegistrationForm() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if ...

"Trigger jQuery animations on and off the screen, with the ability to

Can a long polling script be automatically paused when a page is left open but not actively viewed, ensuring that only the active tab has the running script? ...

When attempting to pass a token in the header using AngularJS, I encounter an issue with my NodeJS server

Error is: Possibly unhandled Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11) at ServerResponse.res.set.res.header 1. All Node.js services were functioning properly before ...

Applying a CSS style to a division element

Can I modify the style attribute of a div element using JavaScript? <div style="color:#0000FF"> <h3>This is a heading</h3> <p>This is a paragraph.</p> </div> I am interested in achieving the following: Changing th ...

Accessing a key using Vuefire within a v-for loop

Recently embarking on the Vue and Vuefire journey, I am experimenting with creating dynamic links to different pages using unique keys as URL IDs. The database reference is configured as let db = app.database(); const postsRef = db.ref('posts') ...

I am looking to dynamically assign an href attribute to a link using a variable within my script. How can I achieve

I am working on displaying an image inside a jQuery slider with the following HTML markup:- <li> <figure> <a href="~/img/big.jpg" class="thumb"> <img src="~/img/small.jpg" alt=""/> <span> ...

What is the best method to place files from a file input into an array in the Firefox browser?

(I am using Vue 3) I have a functionality where I add files from an input file to an array, and then conditionally render these file names. Everything works perfectly on Chrome, but I encountered an issue with Mozilla Firefox. In Firefox, the array of file ...

When using nextjs, there is an issue that arises when attempting to define the property 'id' using context.params.id. This results in

Attempting to retrieve data from a JSON file (response.json) hosted on localhost:8000/response.json. Below is the code snippet from pages/test.js: import React from "react"; import Link from "next/link"; import Image from "next/ima ...

Tips on preventing right-click actions in jqGrid

While utilizing onSelectRow in a jqGrid, I have noticed that it functions properly when clicking with the left mouse button. However, when right-clicking, it still triggers the function. My aim is for the right-click to perform its usual action (such as di ...

Concealing an element from a separate module

In the angularjs single page application project that I'm working on, there are two modules: module-'A' and module-'B'. Each module has its own view templates. The view template of module-'B' contains a div with id="sit ...

Leveraging $.ajax for fetching HTML and converting it into a JavaScript array

let urlPath = window.location.pathname.split("/"), idFromUrl = urlPath[2], dataEndpoint = "/bulletins/" + idFromUrl + "/data"; $.ajax({ url: dataEndpoint, type: "get", dataType: "html", success: function (data) { let dataAr ...

Refreshing a webpage post initial loading using Next.js

Having trouble with my checkout route ""./checkout"" that displays embedded elements from Xola. The issue arises when using client-side routing as the checkout page requires a manual refresh to load correctly and show the Xola elements on the DOM ...

The API call for useState is coming back with a response of an array

I'm currently facing a challenge with fetching and displaying data from an API. When I check the state variable called "dataFromApi" using console.log, everything seems to be working fine as I see an array of multiple objects being returned. However, ...

React animation failing to render underline animation

After tinkering with the underline animation while scrolling down on Codepen using Javascript, I successfully implemented it. You can check out the working version on Codepen. This animation utilizes Intersection Observer and a generated svg for the underl ...

Sharing an array between two sibling components

Within my 'Home' component, users have the ability to create QR codes. I have implemented a method that generates an array of these QR items. Now, the challenge lies in passing this array to another component that is a sibling and not located wit ...

Execute JavaScript using Ajax technology

Although it has been discussed previously, my knowledge of javascript is quite limited, so I find myself a complete beginner. I am currently utilizing a javascript code that sends variables to a php file, and the information is then loaded into the current ...