Divide array elements into groups based on their values in JavaScript

Within my JavaScript API, I have received a result that requires me to group elements by date in order to perform further calculations. The result is as follows:

[
  "2020-01-24 08:00:00",
  "2020-01-23 14:00:00",
  "2020-01-23 12:00:00",
  "2020-01-23 09:00:00",
  "2020-01-22 09:00:00",
  "2020-01-22 13:00:00"
]

The grouping should be done like this :

[ "2020-01-24": 1 value,
  "2020-01-23": 3 value,
  "2020-01-22": 2 value ]

In addition, I also need to search within the array and extract any values with a count of >= 3 to place them in another array.

Answer №1

Utilize Array.prototype.reduce to iterate through the array and increment the value in the accumulator.

var y = [
  "2020-02-15 10:00:00",
  "2020-02-14 09:00:00",
  "2020-02-14 12:00:00",
  "2020-02-13 08:00:00",
  "2020-02-13 11:00:00",
  "2020-02-12 16:00:00"
];

const modifiedDate = y.reduce((temp,elem) => {
  const dateVar = elem.split(" ")[0];
  temp[dateVar] = (temp[dateVar] || 0) + 1;
  return temp;
}, {});

console.log(modifiedDate);

Answer №2

Take a look at https://lodash.com/docs/4.17.15#groupBy for assistance.


const dates = [
  "2020-01-24 08:00:00",
  "2020-01-23 14:00:00",
  "2020-01-23 12:00:00",
  "2020-01-23 09:00:00",
  "2020-01-22 09:00:00",
  "2020-01-22 13:00:00"
]

const groupedDates = _.groupBy(dates, date => date.split(' ')[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

Angular Compilation Blocked Due to Circular Dependency Error

Currently, I am utilizing WebStorm as my IDE to work on a personal project that I envision turning into a game in the future. The primary goal of this project is to create an Alpha version that I can showcase to potential employers, as I am actively seekin ...

What is the best way to format a date as "2020-01-16 07:29:43.657519000 Z" using JavaScript?

Upon discovering a format 2020-01-16 07:29:43.657519000 Z in a project, I am curious about the significance of the numbers 657519000 and how to replicate this precise format using JavaScript. When attempting new Date().toISOString(), I receive 2020-05-27T2 ...

JS The clipboardData in ClipboardEvent is perpetually void

I am trying to retrieve files using CTRL+V from the ClipboardEvent in Angular6, but I am encountering an issue where the clipboardData is always empty regardless of whether I test images or text. This problem persists even when tested on the latest release ...

Ways to Enhance jQuery Efficiency in a Broader Sense

Utilizing jQuery functions is a common practice for us. However, there has been talk about its impact on performance. While it is simple to write, understand, and maintain, some say that it is slower compared to using traditional raw JavaScript code. But ...

navigate a specific web address using Express routing

Is there a specific regex pattern that should be used in an Express application to match a URL? For example, if the endpoint is www.mydomain.com/v1/https://www.url-to-be-matched.com. I am aiming to accept https://www.url-to-be-matched.com as parameters. H ...

Maximizing the efficiency of threejs through combining and selecting items

In my exploration of three.js optimization, I discovered that reducing the number of draw calls is crucial for improving performance. One way to achieve this is by consolidating geometries through the use of GeometryUtils.merge. Although this optimization ...

Enhancing FileUpload functionality in ASP.NET with jQuery function prior to postback

My webpage is built with .aspx and contains the following code: .. <form id="frm" runat="server"> <asp:FileUpload runat="server" id="fileupload" onchange="browsed()" /> <asp:Button runat="server" OnClick="Upload_Click" id="uploadb ...

Unexpected error from API call detected within Mint localhost Template Kits elements

Hello Everyone, hope you're all having a good day! Recently, I installed the Elementor and Envato Elements plugins on my localhost Linux Mint WordPress setup. After configuring permalinks and other settings in WordPress, I proceeded to browse Templat ...

Using CSS properties as false values within React applications

Can you provide guidance on using conditional styles with conditional operators? What would be the ideal code example? Is it possible to use non-CSS values? margin: isOpen ? '10px' : undefined margin: isOpen ? '10px' : 'initial&a ...

Activate the date-picker view when the custom button is clicked

Utilizing this library for date-picker functionality has been quite beneficial. I am currently working on a feature that involves opening the date-picker upon clicking a custom button. The default input is functioning properly. <input name="pickerFromD ...

Display outcome generated by JavaScript in the input box

I've successfully implemented a date/time picker in a form. Using JavaScript, I've created a script to calculate the difference between two date fields and display it in a third field labeled Course Duration. However, I'm encountering an i ...

Change the date string to year, month, and day

When using Ajax's getResponseHeader("Last-Modified"), it returns a date string with the format displayed below: Thu Oct 13 2016 13:05:17 GMT+0200 (Paris, Madrid, sommartid) I am wondering if it is achievable in javascript to extract the year, month, ...

Issue with getBytes not triggering .OnSuccess or .OnFailure events when using a onDataChange listener in Firebase

When running an addValueEventListener on my Firebase database triggered by a button click, a datasnapshot with user data is retrieved. This data is then processed in a for loop to save the data points into an SQLite database. The final step involves checki ...

Opencart: The Key to Your Website's Success

Quick question - I have a Java snippet that needs to be added to my OpenCart checkout page before the closing </body> tag. However, I cannot locate the </body> tag in the checkout.tpl file of OpenCart. Can anyone guide me on where to find thi ...

Javascript editing enhancement for real-time changes

Are there any tools for in-place editing of Javascript code? I'm looking for something similar to Firebug, which is great for instant CSS editing and previewing but doesn't have the capability to edit JavaScript directly. Is there a tool or addon ...

After the initial iteration, the .length function ceases to function properly when

A validation method is set up to check the length of a user input field. It functions properly on the initial try, but does not update if I go back and modify the field. $("#user").blur(function () { if ($("#user").val().length < 3) { $("#userval ...

Activate a specific table by inputting the data from a different table

I am attempting to automate the calculation of a table by inputting values from another table. There are two tables involved; the first one has an input field named profit_rate, and the second one is supposed to calculate cost * currency_rate * profit_rate ...

If the background color is blue, then element class will be added

Currently exploring the realm of JavaScript, I am tackling a challenge with adding a class to an element based on its background color. Specifically, I aim to add a class to elements with a background color set to rgb(32, 44, 62). However, my current imple ...

Utilize res.render in Node.js to pass multiple data arrays to the view

I am facing an issue with populating two separate selects in my view with different arrays. Can anyone guide me on how to pass two distinct JSON objects using res.render? I have attempted the method below without success. const result1 = {data1: "val ...

How to create collapsible and expandable HTML table columns using the <th> element?

I've searched far and wide for a solution to this conundrum and come up empty-handed. I have a HTML table with a total of 13 columns. The 7th column, labeled Number of Tops, is a sum of columns 8-11: # Short-sleeve, # Long-sleeve, # Sweaters, # Jacket ...