Is there an array containing unique DateTime strings?

I am dealing with an Array<object> containing n objects of a specific type.

{
  name: 'random',
  startDate: '2017-11-10 09:00',
  endDate: '2017-11-23 11:00'
}

My goal is to filter this array before rendering the results into a new Array<object which only includes the unique values of the startDate field (e.g., 2017-11-10 09:00 and 2017-11-10 10:00 are not unique) along with a counter indicating how many times each unique date appears in the data array. How can I accomplish this task?

Answer №1

var dateEntries = [{
  name: 'foo',
  startDate: '2017-11-10 09:00',
  endDate: '2017-11-23 11:00'
}, {
  name: 'bar',
  startDate: '2017-11-10 09:01',
  endDate: '2017-11-23 11:00'
}, {
  name: 'baz',
  startDate: '2017-11-10 09:00',
  endDate: '2017-11-24 10:00'
}, {
  name: 'biz',
  startDate: '2017-11-10 09:01',
  endDate: '2017-11-25 09:00'
}, {
  name: 'quick',
  startDate: '2017-11-10 09:00',
  endDate: '2017-11-23 11:00'
}, {
  name: 'brown',
  startDate: '2017-12-10 09:00',
  endDate: '2017-11-23 11:00'
}, {
  name: 'fox',
  startDate: '2017-12-10 10:00',
  endDate: '2017-11-23 11:00'
}];


var startDateOccurrences = dateEntries.reduce(function (tempCollector, date) {
  var
    startDateStr = date.startDate,
    count = tempCollector.directory[startDateStr];

  if (!count) {
    count = tempCollector.directory[startDateStr] = {
      startDate : date.startDate,
      occurrence     : 0
    };
    tempCollector.list.push(count);
  }
  count.occurrence += 1;

  return tempCollector;

}, {

  directory: {},
  list:     []

}).list;


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

Answer №2

To start, you can utilize the Array.prototype.reduce() method in the following manner:

const dates = [{
    name: 'example',
    startDate: '2018-05-20 10:00',
    endDate: '2018-05-21 15:00'
  },
  {
    name: 'example',
    startDate: '2018-05-22 09:00',
    endDate: '2018-05-23 11:30'
  },
  {
    name: 'example',
    startDate: '2018-06-01 08:00',
    endDate: '2018-06-02 18:00'
  },
  {
    name: 'example',
    startDate: '2018-05-20 10:00',
    endDate: '2018-05-21 15:00'
  }
];

const hash = dates.reduce((a, c) => (a[c.startDate] = ++a[c.startDate] || 1, a), {});
const uniqueDates = Object.keys(hash).map(k => ({ startDate: k, counter: hash[k] }));

console.log(uniqueDates);
.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

What is the best way to prevent images from being loaded with broken links?

Currently, I am working on a new feature that involves rendering images from servers. In the process of aligning these images, I noticed an excessive amount of white space due to loading images with broken links. https://i.stack.imgur.com/jO8BR.png Here ...

The logical operator malfunctions following a computation

var sub_response_type = {"survey_question":["Test lable"],"responseTypeText":"Exit label","select_param_type":[">","<"],"questions_id":["7","8"],"select_param_value":["12","34"],"radio_type":["&&"]}; var order = ['questions_id' ...

Easily accessible jQuery tabs with the option to directly link to a specific tab

I currently have tabs set up on my webpage. The code for these tabs is as follows: $('ul#tabs li a').click(function(){ var id = $(this).attr('id'); var counter = 1; $("ul#tabs a.current").removeClass('cur ...

What causes the function to return null when using router.get('/:x',..), whereas router.get('/foo/:x',...) works perfectly fine?

After weeks of struggling to identify the root cause of my issue, I finally pinpointed it. Now, I'm curious to understand the reason behind this behavior. I constructed an api for my mongodb server following the techniques I learned in school, utiliz ...

Using style binding and ngStyle doesn't appear to be effective for setting a background image within a DIV element in Angular5

After facing difficulties in customizing the spacing of Angular material cards, I decided to create my own cards. However, during this process, I encountered an issue where I needed to set an image as a background inside a div. Despite trying various CSS ...

Retrieve the variable declared within the event

How can I access a variable set in an event? Here is the code snippet: $scope.$on('event_detail', function (event, args) { $scope.id = args; console.log($scope.id); // This prints the correct value }); console.log($scope.id); // ...

Encountering a problem while trying to run npm publish with public access, error code E

I've encountered an issue when attempting to publish a scoped package on npm, where I consistently receive this error via the CLI: npm ERR! code E403 npm ERR! 403 403 Forbidden - PUT https://registry.npmjs.org/@username%2fdynamic-ui-elements - Forbidd ...

The Jquery slider panel seems to be stuck open even after I switched its CSS orientation from right to left

I am following up on a previous question, which can be found here. After fixing the jQuery code, I decided to change the panel slider to open from the left side instead of the right. I modified the class from "cd-panel from-right" to "cd-panel from-left". ...

What is the purpose of assigning scope.property to scope.property() in order for the expression to function properly?

I have encountered an interesting situation with the directive below. In order for my expressnum function to work in the template, I had to include the line scope.expressnum = scope.expressnum();. It does what I need it to do, but I'm not entirely sur ...

Maintain the specific type based on the provided data, rather than the default value, when a related generic is defined

When it comes to unit tests, I prefer a more flexible approach with dynamic generic types that eliminate the need for type casting. I want T to be open-ended, but if I specify a type, I expect to receive an exact match. For R, I need it to precisely matc ...

Here are the steps to divide an array of objects into separate objects based on their keys

The data I currently have is formatted like this: [{ "Consumer": [{ "Associated ID": "JSUDB2LXXX / BIC 7503 / US", "Parent Consumer": "7503" }], "Owner": [{ &qu ...

The installation of "npm" was completed successfully, however there seems to be an issue when

I am currently facing an issue while trying to set up http-server, bower, and grunt on my Windows machine. After successfully installing them using npm install, I encountered a 'command not found' error when attempting to run the commands. Even a ...

Using Typescript to deliver the parent component's props to its children prop

I have a goal to create a versatile component that can accept different props based on its usage in the project. The component should output its children prop along with all the given props (flow-through) and potentially some new constants calculated based ...

Generate a text input field within a dropdown menu

Below is an example of my basic HTML code for a drop-down list: <span id="Div_List"> <label for="Gender">For:</label> <select name="Gender" id="Sex"> <option value="1">1000mtr</option> <option val ...

Tips for creating a curved shape using fabric.js

I am encountering an issue while trying to draw an arc using a circle with a start and end angle in my code. Here is the snippet I am working with: var circle = new fabric.Circle({ radius: 30, left: 20, top: 20, fill: " ...

Encountering a Node.js error while using ssh2: ECONNRESET read error

I have been attempting to utilize npm's ssh2 package to establish an SSH connection and remotely access a machine. The code functions properly for connections from Windows to Linux/MacOS, but encounters issues when connecting from Windows to Windows ( ...

What is the best approach to implementing a 30-minute expiration for a JWT token?

I'm having trouble setting the expiration time for my jwt token to 1 minute in my code. How can I resolve this issue? It seems a bit confusing...I want the token to expire after 1 minute. (auth.js) const express = require("express"); const p ...

Typescript does not support index signatures with bracket property accessor when importing using the `import * as`

Currently learning typescript and in the process of converting a large program from javascript. While fixing errors and adding types, I'm stuck on this one particular issue. Here's myModule.ts: export const foo = { ... } export const bar = { .. ...

Having trouble displaying Ad-Gallery Loader.gif?

Having trouble with an image gallery I found at . The loader.gif image isn't showing up in IE9, just a red X. Being new to JavaScript, I'm struggling to fix this issue located at the top of the JavaScript file. (function($) { $.fn.adGallery = ...

Updating files in a Next.js project and automatically refreshing the page without the need to rerun 'npm run'

For a while now, I've been developing websites using a traditional LAMP stack with javascript (including jQuery) for the frontend. Recently, I decided to explore using javascript for the backend as well and started learning next.js. In the older meth ...