Discover distinct values within an array based on the data

I have an array that contains the data of users who joined in the last seven days from the current date. For example:

users=['19 Dec', '21 Dec', '21 Dec']
This array shows that three users joined in the last 7 days. I am attempting to identify the unique occurrences using this function. `

 let occurrences = users.reduce(function (acc, curr) {
              return acc[curr] ? ++acc[curr] : (acc[curr] = 1), acc;
            }, {});

`

The returned object consists of the following key-value pairs: {19 Dec: 1, 21 Dec: 2} My goal is to complete the missing values in the object with 0 and their respective dates. Therefore, the final output should be:

{19 Dec: 1, 20 Dec: 0, 21 Dec: 2, 22 Dec: 0, 23 Dec: 0, 24 Dec: 0, 25 Dec: 0}

Could someone please assist me in resolving this issue?

I anticipate filling the missing values in the object with 0 along with their corresponding dates. As a result, the final output should look like this:

{19 Dec: 1, 20 Dec: 0, 21 Dec: 2, 22 Dec: 0, 23 Dec: 0, 24 Dec: 0, 25 Dec: 0}

Answer №1

Maybe you can try something similar to this approach. I've made some tweaks to the code inspired by this solution on Stack Overflow. The formatting was adjusted based on another Stack Overflow answer.

To start off, let's create an array that includes the past 7 days.

Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

function getDates(startDate, stopDate) {
    var dateArray = [];
    var currentDate = startDate;
    while (currentDate <= stopDate) {
        var calendarDay = currentDate.getDate();
        var monthName = new Intl.DateTimeFormat('en-US', options).format(currentDate);
        dateArray.push(calendarDay + " " + monthName);
        currentDate = currentDate.addDays(1);
    }
    return dateArray;
}

var options = { month: 'short' };
var end = new Date();
var start = end.addDays(-7);

var dateArray = getDates(start,end);

Now, let's assume you have a JSON object with dates and corresponding user counts as values.

let occurences = {
    "19 Dec": 1,
    "21 Dec": 2
};

We'll create a copy of this object for manipulation purposes. This step is optional, but it provides more flexibility.

var copyOcc = occurences;

Next, we'll iterate through our dateArray and update the user counts based on matching dates in occurences.

for(var i = 0; i < dateArray.length; i++) {
    // Add missing keys to the copy
    if(!copyOcc.hasOwnProperty(dateArray[i])) {
        copyOcc[dateArray[i]] = 0;
    }
}

console.log(copyOcc);

The resulting output will look like:

{
  18 Dec: 0,
  19 Dec: 1,
  20 Dec: 0,
  21 Dec: 2,
  22 Dec: 0,
  23 Dec: 0,
  24 Dec: 0,
  25 Dec: 0
}

Feel free to explore the complete script on JSFiddle.

Answer №2

This is an alternative implementation in pure JavaScript:

const usersList = ['19 Dec', '21 Dec', '21 Dec']
const monthsAbbreviation = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

// Fetch previous days' data, defaulting to 7 days
function getPreviousDaysData(numOfDays = 7) {
  const dataObj = {};
  for (let i = 0; i < numOfDays; i++) {
    const currentDate = new Date();
    currentDate.setDate(currentDate.getDate() - i);
    dataObj[formatDate(currentDate)] = 0;
  }
  return dataObj;
}

// Format the date
function formatDate(date) {
  return `${date.getDate()} ${monthsAbbreviation[date.getMonth()]}`
}

// Create object for previous 7 days
const previousDaysData = getPreviousDaysData(7);

// Calculate occurrences
const occurrences = usersList.reduce(function (accumulator, current) {
  accumulator[current] ? ++accumulator[current] : (accumulator[current] = 1);
  return accumulator;
}, Object.assign({}, previousDaysData));

// Log the occurrences to console
console.log(occurrences)

Answer №3

My recommendation is to implement the following solution using typescript:

  1. First, create an array that stores the dates of the last 7 days in the format found in the users array.
  2. Next, iterate through these 7 dates using the map operator and apply the filter method to determine the number of user registrations on each day.
  3. The function getDailyRegistrations() will output an object with the dates as keys and the corresponding number of user registrations as values.
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
users = ['19 Dec', '21 Dec', '21 Dec'];


getDailyRegistrations(numberOfDays: number = 7): any {
    let occurrences: any = {};
    this.getLastXDates(numberOfDays)
        .map(d => this.formatDate(d))
        .forEach((d: string) => {
            occurrences[d] = this.users.filter(u => u === d).length;
    });
    return occurrences;
}


/* Helper methods */

private getLastXDates(numbOfDays: number): Date[] {
    return Array.from(Array(numbOfDays).keys()).reverse().map(i => {
        const d = new Date();
        d.setDate(d.getDate() - i);
        return d;
    });
}

private formatDate(d: Date): string {
    const day = d.getDate();
    const month = this.months[d.getMonth()];
    return `${day} ${month}`;
}

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

Design divs that automatically adjust in size based on mouse-over activity

After searching extensively, I have come across several posts that are somewhat similar to my question, but none of them provide a satisfactory answer. I am interested in resizing divs and their contents in a way similar to the design of the new lafitnes ...

Troubleshooting Issue with React Function's Conditional Component Rendering

Currently, I am working on honing my skills in React using Codesandbox. My goal is to conditionally display a functional React component inside a function (within a class-based component) that triggers when a button is clicked. If you'd like to take ...

The component data fails to reflect the updated value following a status change due to not properly retrieving the new result from the POST function

Below is the Vue.js 2 code snippet for sending data to the backend. The vuex library was used to manage the data status. After using the POST function, the result returned from the backend updates the value of sampleId. This value is auto-generated by the ...

Python script utilizing Selenium to load only JavaScript content and excluding full HTML rendering

As I navigate through the link , I am on the lookout for the search bar marked with the class "search-field". The HTML snippet in question is as follows: from selenium import webdriver import time driver = webdriver.Firefox() driver.get("https://www.takea ...

Encountering an error stating "unable to access properties of undefined (reading 'redirectUri')"

I am currently working on fetching details from Okta and saving them in a Store. My code includes an @effect that triggers a service file named a-service.ts. Inside the service constructor, I call the Okta library as shown below: @Injectable() export clas ...

What measures can I take to protect the use of React components that may not be present?

For my project, I am planning to receive icons/svgs as react components from a folder created by the backend. Additionally, there will be a WAMP (bonefish/autobahn) solution where I will be provided with the name of an icon to use (even though this may see ...

Resolving route data in Angular 2 and above

When retrieving data from an API in an Angular route resolver, I encountered a problem where if there was an error due to a stale token, I needed to refresh the token and then retry the API call. Below is the code snippet illustrating this scenario: impor ...

Enhance your automation with the powerful combination of Java,

I am looking to retrieve data from a specific Russian gambling website using String information. Below is the code I have written for this purpose: import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.ope ...

Resize all types of content using a "zooming" container

Is there a way to create a magnifying effect without duplicating content and still keep the underlying elements clickable? Check out this jsfiddle example I am looking for a solution to scale the underlying div within the magnifying zoom without cloning ...

Trouble with importing React JSX from a separate file when working with Typescript

This problem bears some resemblance to How to import React JSX correctly from a separate file in Typescript 1.6. Everything seems to be working smoothly when all the code is contained within a single file. However, as soon as I move the component to anoth ...

Testing the mirkoORM entities at a unit level

Trying to perform a unit test on a method within a MikroORM entity, I am attempting to populate a mikroORM collection field with test data. Specifically, I am using jest for this task: describe('Team Tests', () => { it('isLeader shoul ...

The Socket.io application is facing deployment issues on the Heroku platform

I have developed a simple chat server using nodejs, socket.io, and express, and now I am attempting to deploy it on Heroku using my Git repository. However, when I access the Herokuapp website for my application (), the display is not as expected: https:/ ...

What is the most effective method for implementing multiple textures in three.js?

After recently transitioning to three.js as my renderer, I am eager to establish a texture mapping system. However, determining the best practice for this task is a bit uncertain for me. Here is the scenario I am dealing with: My levels consist of numero ...

Sending AJAX information to multiple pages

I have created an HTML page where I am struggling to pass two variables using the POST method to a PHP page. The PHP page is supposed to accept these variables and then call an API to retrieve data based on them. However, my challenge is in receiving this ...

What is the best way to dynamically add getJSON's data to a div whenever the loadmore button is clicked?

When a page loads, my getJSON function displays its output in a div called myDiv. Now, I am looking to add a button at the bottom of the page. When the user clicks this button, I want to trigger another call to getJSON. Each time the button is clicked, I ...

Can someone provide an explanation for this JavaScript function: What is the purpose of $this = $(this)

A user named "mu" kindly provided me with the following code snippet, which I found quite interesting. However, as a newcomer to this topic, I have a few questions that I'm hoping someone can help clarify. Given the code snippet below: function() { ...

Using Javascript to convert an SVG file into DOM elements

Seeking assistance with uploading an SVG file and then inspecting or parsing it to utilize the elements and values within the DOM. After extensive searches, I've only found information on parsing from the DOM itself. Is this task feasible? If so, cou ...

Tips for retrieving the posted object in angularJS

My current challenge involves creating an object with a defined name, posting it into a database, and then immediately finding its position and obtaining its id. However, I have noticed that using "get" right after "post" retrieves the data before it' ...

Real-time data not instantly stored using socket.io

In my current issue, whenever I receive a message with the action stop, I encounter a problem specifically with the setTotalScore function. Initially, the totalScore is set to 0, and upon receiving the message, it should update to match the user.score. How ...

Fixing blurry text on canvas caused by Arbor.js mouse event issues

Currently, I am utilizing arborjs in my project. The text within the canvas is created using fillText in html5. While everything functions correctly on a Retina display MacBook, the text appears blurry. To address this, I applied the following solution: v ...