Tally of specified time frame

I have a collection of dates presented as follows:

[ "2020-08-20", "2020-08-20", "2020-08-21", "2020-08-24", "2020-08-25", "2020-08-25", "2020-08-25", ]

and I am in need of segregating consecutive identical dates into distinct ranges.

For instance, the desired output should be:

{date: "2020-08-20", period: 1-2}, {date: "2020-08-21", period: 3-3}, {date: "2020-08-25", period: 4-4},
{date: "2020-08-25", period: 5-7}

or simply put:

{date: "2020-08-20", period: 1-2},{date: "2020-08-25", period: 5-7}

If anyone could offer assistance with this task, it would be greatly appreciated. I attempted to utilize momentjs library for this purpose but encountered some challenges :(

Thank you in advance for any help provided

Answer №1

When analyzing the sorted date example provided, I recommend utilizing a 2 pointer solution:

Scenario 1:

var data = ["2020-08-20", "2020-08-20", "2020-08-21", "2020-08-24", "2020-08-25", "2020-08-25", "2020-08-25"];

let i = 0, j = 1;
var res = [];
while (i < data.length) {
    if (data[i] == data[j]) {
        j += 1;
        //scan rest
        while (data[i] == data[j]) {
            j += 1;
        }
        j -= 1;
        res.push({ date: data[i], period: (i + 1) + "-" + (j + 1) });
        i = j + 1;
        j = i + 1;
    } else {
        res.push({ date: data[i], period: (i + 1) + "-" + (i + 1) });
        i += 1;
        j += 1;
    }

}
console.log(res);

Scenario 2:

var data = ["2020-08-20", "2020-08-20", "2020-08-21", "2020-08-24", "2020-08-25", "2020-08-25", "2020-08-25"];

let i = 0, j = 1;
var res = [];
while (i < data.length) {
    if (data[i] == data[j]) {
        j += 1;
        while (data[i] == data[j]) {
            j += 1;
        }
        j -= 1;
        res.push({ date: data[i], period: (i + 1) + "-" + (j + 1) });
        i = j + 1;
        j = i + 1;
    } else {
        i += 1;
        j += 1;
    }

}
console.log(res);

Answer №2

Here is a straightforward approach that identifies unique values in a list and then determines their periods by referencing the first and last occurrences of each value within the original array.

This method assumes that the initial list is sorted. If there are scenarios where multiple periods exist for the same date due to other intervening values, an alternative solution would be necessary along with potential specification updates.

const extractUniqueDates = (dates) =>
  [...new Set(dates)] // retrieve an array of distinct dates
    .map(date => ({   // transform each into a {date, period} object
      date, 
      period: `${dates.indexOf(date) + 1}-${dates.lastIndexOf(date) + 1}`
    }))
      
const inputDates = [ "2020-08-20", "2020-08-20", "2020-08-21", "2020-08-24", "2020-08-25", "2020-08-25", "2020-08-25"]
  
console.log(extractUniqueDates(inputDates))
.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

Rule for jQuery validation based on variables

I am facing an issue with validation of login asynchronously in my HTML form using the jQuery Validation Plugin. I would like to trigger a request for login validity on blur, and validate it upon receiving a response. Below is the code snippet: var login ...

"Repeatedly encountering 'undefined' when subscribing to the selected option of a select list in Knockout.js

In my dropdown list, I have prepopulated a selection of strings. My select list is bound as follows: <select id="industryDropDown" data-bind="options: $root.orgIndustrySuggestions, value: $root.selectedIndustryTag, optionsCaption: ''"> ...

What is the most effective way to transfer a Mongoose Collection to a function in a JavaScript file?

Currently, I am working on a project that involves creating a search functionality for a motorcycle database. This search will be similar to the one found on Revzilla.com under My Garage. The form for this search will be used in multiple parts of the proje ...

Sending a parameter to a confidential npm module

I've developed a custom npm module that can be used in my applications by including this code snippet in the HTML: <app-header-name></app-header-name> Here is the TypeScript code inside the npm package: import { Component, OnInit } from & ...

What could be causing the issue of $.ajax being undefined while utilizing jQuery in Node.js?

I'm currently testing a module on Node.js that is meant for client-side use. In order to make $.ajax work, I need some guidance. To begin with, I have installed jQuery on the project using: $ npm install jQuery Despite this, when I try to access $. ...

Obtain the $httpProvider from jQuery in order to intercept and manipulate messages

I am working on an Angular application that utilizes third-party JavaScript code, which I cannot modify. My goal is to intercept the HTTP messages from outside of Angular. I have managed to access the controller and injector, and retrieve the $http servic ...

What is the best way to incorporate an array of elements into Firebase?

How can I store data from an array to Firebase in a simple manner? Let's say I have an array of elements. function Something() { var elements=new Array() elements[0]=10; elements[1]=20; elements[2]=30; database = firebase.databas ...

Uh oh! An error occurred while trying to create the ngFileUpload module

After using NuGet to install Angular File Upload 12.2.13, I made sure to inject the dependencies correctly. However, despite this, I keep encountering the following error: angular.js:63 Uncaught Error: [$injector:modulerr] Failed to instantiate module c ...

Is it possible to access the operating system's native emoji picker directly from a website?

While there are numerous javascript plugins and libraries available for allowing users to select emojis for text inputs, both Windows and Mac operating systems already have their own native emoji pickers accessible via ⊞ Win. or CTRL⌘Space. Is there a ...

The inclusion of react-helmet in my Gatsby website is leading to an issue where the element type is considered invalid

Incorporating the Layout component in my app has significantly improved the styling. This is where I introduced react-helmet. This is how the component looks: import React from 'react'; import { Global, css } from '@emotion/core'; im ...

Dividing an Image into segments using Javascript

I'm currently working on a basic Jigsaw puzzle project. To achieve this, I am required to divide the image I've selected into 20 separate pieces. I was wondering if there is a method in Javascript that can automatically cut an image into 20 equal ...

What is the equivalent of specifying globalDevDependencies for npm @types packages in typings?

I am looking to update a project using tsc@2 and remove typings from my toolchain. Updating common dependencies is easy as they are listed in my typings.json file: "dependencies": { "bluebird": "registry:npm/bluebird#3.3.4+20160515010139", "lodash": ...

Implementing Image Tagging in JavaScript

Is there a way to create a drag selection box with JavaScript? I'm referring to the functionality where clicking and dragging the left mouse button draws a "wire" (not sure of the technical term) similar to your desktop. Ideally, this action would t ...

JavaScript object conversion to Java Model is proving to be a challenge

When looking at my Spring controller and client-side Javascript code, I noticed that the Javascript object is having trouble reaching the Spring controller in Object form. Here is a snippet of my Controller code: @RequestMapping(value = "/addRating", meth ...

Mouse over effect to highlight the crosshair on a table

My code currently enables a crosshair function, but I am looking for a way to limit the highlight effect only within the cursor (hover) area. Instead of highlighting in a "cross" shape, I would like it to show a backward "L" shape. This means that the hig ...

Unable to retrieve /ID from querystring using Express and nodeJS

I am brand new to the world of Express and nodeJS. I have been experimenting with query strings and dynamic web pages, but I keep getting an error saying that it cannot retrieve the ID. I'm completely lost as to where I might have made a mistake. An ...

Tips for creating text that adjusts to the size of a div element

I'm currently working on developing my e-commerce website. Each product is showcased in its own separate div, but I've encountered a challenge. The issue arises when the product description exceeds the limits of the div, causing it to overflow ou ...

When attempting to assign a 'string' type to the @Input property, I am receiving an error stating that it is not assignable to the 'PostCard Layout' type

Encountering an issue The error message 'Type 'string' is not assignable to type 'PostCard Layout'' is being displayed A parent component named page-blog.component.html is responsible for defining the class styles and passi ...

choosing a specific element within an HTML string stored in a variable

I have a variable containing HTML string data like this: var htmlstring = "<div><div class='testdiv'>924422</div></div>" My goal is to extract the content of the div with a specific class, in this case .testdiv. How ca ...

Enable interactive features on collapsible navigation links

The original code included data-toggle="tab", but I decided to switch it to collapse. This change worked perfectly for my needs. Now, I am looking to add the "active" class to the nav-link element for CSS styling purposes. I have experimented with a coup ...