What is the best way to tally the occurrences of a specific object in a list?

I am looking for a way to analyze a list of dates that looks something like this:

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

How can I determine the count of duplicate items in the list?

For example:

{date: "2020-08-20", count: 2},
{date: "2020-08-21", count: 1},
{date: "2020-08-24", count: 1},
{date: "2020-08-25", count: 3},

Any assistance would be greatly appreciated. Thank you!

Answer №1

let datesArray = [ "2021-09-15", "2021-09-16", "2021-09-16", "2021-09-17", "2021-09-18", "2021-09-18", "2021-09-19" ] 

const resultArray = []

datesArray.forEach(date => {
  const idx = resultArray.findIndex(r => r.date === date)
  if (idx === -1) {
    resultArray.push({
      date: date,
      count: 1
    })
  } else {
    resultArray[idx].count++;
  }
})

console.log(resultArray)

Answer №2

To tally the occurrences, utilize the array reduce function. Iterate through the string array and calculate the frequencies. Finally, display the outcome using the Object.values function.

const data = [
  '2020-08-20',
  '2020-08-20',
  '2020-08-21',
  '2020-08-24',
  '2020-08-25',
  '2020-08-25',
  '2020-08-25',
];

const result = data.reduce((prev, curr) => {
  const previous = prev;
  if (!previous[curr]) previous[curr] = { date: curr, count: 1 };
  else previous[curr] = { date: curr, count: previous[curr].count + 1 };
  return previous;
}, {});
console.log(Object.values(result));

Answer №3

One way to achieve this is by using the following code snippet:

    const datesArray = [ "2020-08-20", "2020-08-20", "2020-08-21", "2020-08-24", "2020-08-25", "2020-08-25", "2020-08-25", ]
    const result = datesArray
      .filter((date, index) => datesArray.indexOf(date) == index)
      .map(date => ({
        date: date,
        count: datesArray.filter(currentDate => currentDate === date).length
      }))
    console.log(result)

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

Enhancing the appearance of input range sliders using before and after elements for custom styling

I'm looking to create something similar to the image linked below https://i.sstatic.net/Czef9.png Note:: The above image features a V-shaped icon, which is what I'm aiming for. Currently, I am utilizing input[type="range"]. The foll ...

deleting the existing marker before placing a new marker on the Mapbox

Upon the map loading with GeoJson data, I have implemented code to display markers at specified locations. It works flawlessly, but I am seeking a way to remove previous markers when new ones are added. What adjustments should be made for this desired func ...

The function is not operational while executing addEventListener

I'm encountering some bugs in my Angular 1.5 project with TypeScript. I'm trying to retrieve the scrollTop value from the .uc-card element. public container = document.querySelector(".uc-card"); In my $onInit, I have: public $onInit() { this ...

Inserting an item into a list

Looking for assistance with this particular scenario: { "EekvB3cnwEzE":{ "name":"hi", }, "Brv1R4C6bZnD":{ "name":"yup", }, "kRwRXju6ALJZ":{ "name":"okay", } } I'm attempting to store each of these objects in an array. Howe ...

A plug-in for TinyMCE that allows users to adjust column widths within a table

We utilize TinyMCE in our content management system (CMS), and our users have expressed interest in being able to adjust the width of a column within a table. While HTML technically does not recognize columns, the Moodle editor HTMLAREA includes a plugin t ...

Generate a string that will be utilized to interpret a JSON response

I can't seem to extract a specific element from a json using a dedicated function. Can someone please assist me with this issue? Here is the fiddle that I have created for reference: http://jsfiddle.net/jonigiuro/N5TTM/2/ CODE: var data = { "res ...

Avoid refreshing the page upon pressing the back button in AngularJS

Currently, I am working on building a web application that heavily relies on AJAX with AngularJS. One issue I am facing is that when the user clicks the back button on their browser, the requests are being re-made which results in data having to be reloa ...

Get the PDF file and access it with Ajax technology

I am facing an issue with my action class that is responsible for generating a PDF. The code snippet shown sets the contentType appropriately. public class MyAction extends ActionSupport { public String execute() { ... ... File report = si ...

Conceal the second click action within the anchor tag

Is there a way to hide the second click event on all anchor tags except those that trigger popupfun? I have a sample page set up. [Check out the JS Fiddle here][1] http://jsfiddle.net/ananth3087/LgLnpvf4/15/ Link Anchor Tags: The page includes two ...

retrieve JSON object from deferred response of AJAX request

After utilizing Ajax to send an item to a SharePoint list, I aim to incorporate the jsonObject received in response into a list of items. Located in AppController.js $scope.addListItem = function(listItem){ $.when(SharePointJSOMService.addListIte ...

Retrieving all selected checkboxes in AngularJS

I am a beginner in angular js and here is my template: <div class="inputField"> <h1>Categories</h1> <div> <label><input type="checkbox" id="all" ng-model="all" ng-change="checkAll();" ng-true-value="1">A ...

Learn how to make a contenteditable div perform tab spacing with a simple keystroke of the tab key

I've been trying to figure out how to make this contenteditable div add tab spacing when I press the tab key, but so far no luck. If anyone has a solution for this issue, please feel free to share. You can use an ID, class, or any other method to get ...

Tips for creating a sophisticated state transition diagram using Typescript

If you have a creative idea for a new title, feel free to make changes! I have two enums set up like this: enum State { A = "A", B = "B", C = "C" } enum Event { X = "X", Y = "Y", Z ...

I'm encountering an issue where Typescript is unable to locate the Firebase package that I

I have a TypeScript project that consists of multiple .ts files which need to be compiled into .js files for use in other projects. One of the files requires the firebase package but it's not being found. The package is installed and located inside t ...

Send data to a webpage and instantly navigate to it

When using the JavaScript code below, I am able to successfully send data to a page named "book.php" via the POST method (as indicated by the alert), but when I try to display the received data on book.php, nothing shows up. <script type="text/javascri ...

What is the best way to obtain the accurate innerHeight of a div on the initial attempt

Within my webpage, there is a hidden sub navigation with its height initially set to 0. This sub navigation contains various sections of sub navs. When a section is clicked, I obtain the name of that section and then retrieve the innerHeight of the corres ...

A dropdown menu generated from a Google Sheet script that allows for the input of custom text alongside predefined

Currently, I am working on creating a dropdown list that not only allows me to select items but also input free text. The code below enables me to choose an item from a selected range in Google Sheets. However, I am looking for a way to incorporate the f ...

Leveraging the power of Nuxt.JS (Vue.JS) and VueX to connect a form to an array of objects within a VueX store

Seeking assistance with binding a form to a list of Defaultsettings obtained from an array of objects in NuxtJs and VueX. The list of Defaultsettings includes: Name defaultsetting (text) Active (a switch button that determines if the defaultsetting will ...

Encrypting data between two Node.js servers

I am looking to create a Node.js daemon that can operate across multiple computers while facilitating message exchange between the daemons. Security is paramount, so I want to ensure the communication is encrypted. However, I am uncertain about which encry ...

Develop a constructor that can be injected

Delving into the world of AngularJS as a beginner, I am starting to grasp the intricacies and distinctions between factory, service, and controller. From my understanding, a factory serves the purpose of returning a "value object" that can be injected. Mos ...