Guide to pairing array elements in JavaScript

To streamline the array, only elements with a value equal to or greater than the set threshold will be retained. These selected elements will then be used to create a new array comprising multiple objects. Each object will consist of two properties: the start and end timestamps.

If consecutive elements have timestamps that are 10 minutes apart, they will be grouped together within the same object. The start timestamp will be that of the first element, while the end timestamp will be the timestamp of the last element in the group plus 10 minutes.

In cases where there are no consecutive elements, the start timestamp will remain as it is, and the end timestamp will be the start timestamp plus 10 minutes.

const data = [{
    timestamp: '2021-11-23T14:00:00+0000',
    amount: 21
  },
  {
    timestamp: '2021-11-23T14:10:00+0000',
    amount: 27
  },
  {
    timestamp: '2021-11-23T14:20:00+0000',
    amount: 31
  },
  {
    timestamp: '2021-11-23T14:30:00+0000',
    amount: 29
  },
  {
    timestamp: '2021-11-23T14:40:00+0000',
    amount: 18
  },
  {
    timestamp: '2021-11-23T14:50:00+0000',
    amount: 17
  },
  {
    timestamp: '2021-11-23T15:00:00+0000',
    amount: 25
  },
  {
    timestamp: '2021-11-23T15:10:00+0000',
    amount: 21
  }
]

const threshold = 25
const aboveThreshold = data.filter(element => element.amount >= threshold)
const workSchedule = []

for (let i = 0; i < aboveThreshold.length; i++) {
  if (i === 0) {
    workSchedule.push({
      start: aboveThreshold[i].timestamp,
      end: aboveThreshold[i + 1].timestamp
    })
  }
  if (i > 0 && i < aboveThreshold.length - 1) {
    if (aboveThreshold[i].timestamp.slice(11, 13) === aboveThreshold[i + 1].timestamp.slice(11, 13)) {
      workSchedule.push({
        start: aboveThreshold[i].timestamp,
        end: aboveThreshold[i + 1].timestamp
      })
    }
  }
  if (i === aboveThreshold.length - 1) {
    workSchedule.push({
      start: aboveThreshold[i].timestamp,
      end: aboveThreshold[i].timestamp
    })
  }
}

console.log(workSchedule)

Ultimately, the desired result would look like this:

[
    {
        start: '2021-11-23T14:10:00+0000',
        end: '2021-11-23T14:40:00+0000'
    },
    {
        start: '2021-11-23T15:00:00+0000',
        end: '2021-11-23T15:10:00+0000'
    }
]

I hope this explanation clarifies the process 😬 Is there a more straightforward approach to achieve this outcome?

Answer â„–1

Utilizing a straightforward reduce function along with the Date object can help you achieve the desired result. Below is an example of how you can implement this:

const filteredData = data.filter(element => element.amount >= threshold);

const timeRanges = filteredData.reduce((accumulator, value) => {
  const endTime = new Date(Date.parse(value.timestamp) + 600000);
  if (accumulator.length === 0) return [{ start: value.timestamp, end: endTime.toISOString() }];
  let timeDiff = Date.parse(value.timestamp) - Date.parse(accumulator[accumulator.length - 1].end);
  
  if (timeDiff <= 10 * 60 * 1000) {
    accumulator[accumulator.length - 1].end = endTime.toISOString();
  } else {
    accumulator.push({ start: value.timestamp, end: endTime.toISOString() });
  }
  
  return accumulator;
}, []);

To learn more about the Reduce Documentation, visit the official Mozilla developer website.

Here is the resulting output based on your input data:

[{
  start: "2021-11-23T14:10:00+0000",
  end: "2021-11-23T14:40:00.000Z"
}, {
  start: "2021-11-23T15:00:00+0000",
  end: "2021-11-23T15:10:00.000Z"
}]

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

Using an external script to modify or call a Vue.js method

My Vue app is constructed using Webpack and includes a few basic computed properties, such as calculating the sum amount from input values. However, I now require the capability to replace the summation function with one stored in a separate file that is n ...

The output from the Moment.js HTTP server is currently experiencing errors and is not displaying the expected

My first time working with JavaScript and the Momentjs library has not been smooth sailing. I am facing an issue where the output is not displaying as required. The goal is to show dates in the format "Day, date month year" (e.g., Tuesday, 14th May 2018). ...

Assign the default value of a Vue prop to the options of its parent component

I have a child component that needs to accept a value given in the component's parent's $options object as a possible default value. In the background, the component should be able to receive its data through a prop or from a configuration. Howe ...

Issue: Angular JS radio input not functioning as expected

Below is the code snippet in question: <div ng-controller="TestController"> <input ng-repeat="item in array" ng-model="selected.name" value="{{item.name}}" type="radio"></input> </div> <script type="text/javascript"> ...

Have you ever wondered how the automatic video play on scroll feature works on Tiktok.com and YouTube shorts when using a mobile device?

My goal with React JS is to develop a website similar to Tiktok, where the video below will automatically play with sound as the user scrolls down. I attempted to set this up using window.addEventListener("scroll",...), but after looking into it further, ...

Having trouble with sending a JSON post request in Flask?

I have a setup where I am utilizing React to send form data to a Flask backend in JSON format. Here is an example of the code: add_new_user(e){ e.preventDefault() var user_details = {} user_details['fname'] = this.state.first_name user_d ...

Error: Incorrect Path for Dynamic Import

Recently, I've been trying to dynamically load locale files based on the locale code provided by Next.js. Unfortunately, every time I attempt a dynamic import, an error surfaces and it seems like the import path is incorrect: Unable to load translatio ...

Setting up TypeScript in Jest without the need for webpack

Currently, I'm developing an NPM module using TypeScript without the use of Webpack for compiling scripts. I need some guidance on configuring Jest to properly run tests with TypeScript files. Any recommendations? // test.spec.ts import {calc} from ...

Make sure to include the environment variable in the package.json file before running Cypress in headless mode

I am trying to determine whether Cypress is running or not within a NextJS application. My goal is to prevent certain http requests in the NextJS application when Cypress tests are running. Currently, I am able to detect if Cypress is running by using the ...

Issue with event delegation when using if-else conditions is not being resolved

I have set up an event listener on an HTML container, and when the user clicks on the play again button, the code inside the 'if' statement should be executed. However, nothing happens when clicking on the play again button and no logs are output ...

Trigger a click (or selection) on a specific dropdown option using jQuery

I am attempting to initiate a click function upon page load using jQuery on a dropdown option within Chosen, in order to activate a subsequent action. Unfortunately, I have not been successful in getting it to work. I have tried the following methods: jQ ...

Tips for concealing the URL in the address bar while using `<a href>` links

I have a variety of documents saved in a folder within an ASP MVC 5 project. Instead of directly linking to the document with an HTML tag, I am utilizing the following ng-href: <a ng-href="~/download/document/{{vm.document}}"></a> By using th ...

Dropdown does not populate with data

HTML content <select class="form-control" tabindex="-1" id="superId" name="superId[]" multiple="multiple" required="required" data-bind="options: SupArray, optionsText: ' ...

Error: Attempting to assign a value to a property of #<Object> that is read-only

I'm working on a task management application and encountering an issue when trying to assign an array of tasks stored in localStorage to an array named todayTasks. The error message being thrown is causing some disruption. https://i.sstatic.net/uFKWR. ...

Utilizing Angular 4: Sharing Data through Services and Components

After transitioning my data from an object in a service to a database connection, I'm facing issues where the data is not reaching the component as expected. To solve this problem, I have set up the service to subscribe to the data retrieved from the ...

Transmitting the data from the input field

I'm currently stuck trying to figure out the logic behind my Ajax form submission. I am attempting to POST my form using Ajax and send certain values in the correct manner. Here is an example of my form: <form method="post" action="~/AJAXcalls/ca ...

Ensuring the type of a specific key in an object

Seeking a more stringent approach regarding object keys in TypeScript. type UnionType = '1' | '2' | '3' type TypeGuardedObject = { [key in UnionType]: number } const exampleObject: TypeGuardedObject = { '1': 1, ...

Troubleshooting a VueJS Problem: Updating $data in the mounted hook

Revision This snippet of Component.vue was extracted from a larger web application where I made a mistake that had significant consequences, all because of a small change I didn't initially notice. An important distinction exists between the followi ...

How can I fetch the ID from a posted AJAX request in PHP?

Is there a way to retrieve the data from an ajax request in PHP? I am able to successfully return a string of data using ajax, but I'm having trouble accessing the variable passed as a json object. How can I access a json object that only contains one ...

Importing JSON Array Information into a MySQL Database

I'm feeling lost when it comes to accessing and importing this data into MySQL. The JSON Data I have is: { "serial_number": "70-b3-d5-1a-00-be", "dateTime": "2020-08-14 20:58", "passReport" ...