Determine the occurrences of a particular element in an array

I attempted to create a script that extracts a row from a spreadsheet filled with dates, converts it into an array, and then counts occurrences of a specific date.

Although I successfully completed most of the script, I encountered difficulties when trying to implement the feature that counts a specific date.

The dates in the array are formatted as follows:

Fri Jan 27 2017 00:00:00 GMT+0100 (MEZ)

The array contains the following dates:

Fri Jan 27 2017 00:00:00 GMT+0100 (MEZ),Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ),Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ),Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ),Mon Jan 02 2017 00:00:00 GMT+0100 (MEZ),,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

The desired output for "Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)" is:

3

Answer №1

const datesArray = ["Fri Jan 27 2017 00:00:00 GMT+0100 (MEZ)", "Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)", "Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)", "Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)", "Mon Jan 02 2017 00:00:00 GMT+0100 (MEZ)"];

const dateToCount = "Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)";

const count = datesArray.reduce((accumulator, currentDate) => {
    return currentDate === dateToCount ? ++accumulator : accumulator;
}, 0);

console.log(count);

Note: To account for varying date formats and lowercases in the dates array, consider parsing the dates like this:

const parsedDateToCount = Date.parse("Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)");
const count = datesArray.reduce((accumulator, currentDate) => {
    return Date.parse(currentDate) === parsedDateToCount ? ++accumulator : accumulator;
}, 0);

Answer №2

If you are working with an array of date strings like the following:

var arr = ["Fri Jan 27 2017 00:00:00 GMT+0100 (MEZ)", 
           "Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)", 
           "Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)", 
           "Wed Jan 11 2017 00:00:00 GMT+0100 (MEZ)", 
           "Mon Jan 02 2017 00:00:00 GMT+0100 (MEZ)"];`

You can use the following code snippet to extract the day from the first element in the array:

var day = new Date(arr[0]);
day = day.getDay() + 1;

To learn more about the Date object and the getDay() method, refer to the following documentation:

Date object reference: http://www.w3schools.com/jsref/jsref_obj_date.asp

getDay() method reference: http://www.w3schools.com/jsref/jsref_getday.asp

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

Vue component failing to re-render after data modification

I'm a Vue beginner and I am attempting to showcase a list of "notes" that should update once a button is clicked (I have manually set the value to add for now). However, after adding a new item to the array, the changes are not reflected on the user i ...

All post processing modules in THREE.js can be imported as ES6 modules, with the exception of OutputPass

I am attempting to recreate this particular instance using modules imported from a CDN. Here is the import map I am working with: <script async src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2c7 ...

Is there a way to trigger a jQuery function using the onRowSelect event in ajax?

I have a jQuery function that is triggered by the 'change' event when a value is selected in a <select> element. However, I no longer need the <select> because I will manually set the value within my jQuery function. My page utilizes ...

What is the best way to search a jsonb array to see if it includes any of the values from a list of queries?

My current table displays as follows: id | companies ----+------------------------------------------------------------------- 1 | {"companies": [{"name": "Google", "industry": &quo ...

The regex pattern is failing to match the input pattern

<input type="text" id="url" name="url" pattern="/ ^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)(amazon)|(flipkart)+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$ /" ...

Discovering the attribute of a DOM element (or, to be more precise, the class of a div)

Here's the code snippet I'm working on: <body class="asdf"> <span>hey! <div class='hideContent'>test</div> the ultimate experience</span> <span id="blarg">original</span> </b ...

Tips for organizing your JSON Structure within ReactJs

In the given example, I have a JSON structure with information about different airlines. The Airline Name is dynamic and we need to separate the JSON into an expected array format. const arr = [ { Airline: "Goair", Departure: "01:50" ...

What techniques can be employed to restrict or define imported data in React through mapping?

Starting my React journey with a single-page application, I am looking to bring in a static collection of personal information like this: { id: '1', link: 'john-doe', name: 'John Doe', title: 'Head of ...

Utilizing Javascript within a PHP while loop to showcase map markers

Is there a way to display multiple database entries in a loop and show them as markers on a map like this: https://i.stack.imgur.com/SwaGP.png I am struggling with looping through JavaScript in PHP to display multiple markers. Is it possible to achieve t ...

open a document and store its contents into a matrix

Here is the content of a file I am working with: 1 100 2 200 3 300 4 400 1 I am trying to convert this data into a matrix and replace missing second numbers with NULL. However, my current program is not functioning as expected. Here is a snippet of the ...

jQuery plugin for uploading multiple files with validation for checking if they are empty or not

I recently downloaded the JQuery Multiple file uploader plugin from this website Before submitting the form, I need to verify whether the file input field is empty or not. <form onsubmit="return validate();"> <input type="file" name="File" class ...

Issue encountered during compilation of JavaScript in Vue framework with Rollup

Struggling to compile my Vue scripts with rollup. The error I'm facing is [!] Error: 'openBlock' is not exported by node_modules/vue/dist/vue.runtime.esm.js, imported by src/js/components/TestButton.vue?vue&type=template&id=543aba3 ...

The method for retrieving a generic type property within a dynamic interface

Is there a way to access a dynamic T property within an interface in order to enhance its typing for generic functions like this: type AnotherType<T extends {}> = T & { prop: boolean; prop2: string; }; interface SpecialInterface<T> ...

How can I turn off a state property?

My goal is to detect if the user is using a device with a screen width smaller than 768px, and if they are, I want to set isTop to false. However, I am encountering some difficulties. Everything seems fine, but I keep receiving this error: TypeError: _t ...

Issue encountered in TypeScript: Property 'counter' is not found in the specified type '{}'.ts

Hey there, I'm currently facing an issue while trying to convert a working JavaScript example to TypeScript (tsx). The error message I keep encountering is: Property 'counter' does not exist on type '{}'.ts at several locations wh ...

What is the best way to integrate the each_slice method in Rails views with React components

In my Parent component Monsters, I am rendering the Monster component. for each monster in @state.monsters React.createElement Monster, key: monster.id, monster: monster, team: @state.team... Within the monster: div className: 'col-md-4' ...

Switch up the placement of the boxes by moving them in different directions, such as

I've been attempting to recreate the button movement demonstrated in this link , but I'm having trouble achieving it. Using CSS animation, I can make the buttons move in a straight line, here's what I have so far: <div id="box" style=&ap ...

Employing the `signInWithRedirect` method with an `authDomain` that does not match the app's domain will result in an incomplete sign-in process, without any error notifications being displayed

I'm currently transitioning from using Firebase's signInWithPopup method to the signInWithRedirect method. After reading through the best practices outlined in this documentation, I realized that not following these practices can result in succe ...

Custom geometry in Three.js raycaster detects incorrect object

I am facing a challenge with the default cube's appearance in wireframe mode, as it is made up of triangles instead of squares. To combat this, I created my own geometry which looks satisfactory. However, I have noticed that the raycaster does not fu ...

The div requires the assignment of the ajax response

Currently, I am creating an image gallery using Ajax to fetch data. The Ajax call sends a parameter and retrieves HTML code in response. Upon verifying the response, it seems to be accurate. If I insert this code into a static DIV element, the gallery fu ...