Comparing strings in arrays using JavaScript

Currently, I am engrossed in a firebase project involving vuejs. My goal is to create a chart that visually represents the number of subscribers per month. The tricky part lies in accurately calculating the number of user profiles created each month. As for the remaining steps, I feel confident in handling them.

My initial approach involves the following:

// Calculating the number of users each month
let months = ['jan', 'feb', 'mar', 'apr', 'may', 'Jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];

this.users.filter(user => {
  let print = user.metadata.creationTime;

  for (var month in months) {
    if (print.indexOf(month) > -1) {
      console.log(user.email)
    }
  }
})

As I tested this solution, I noticed that the console output displayed duplicate records for each month.

Considering this situation, I am pondering whether there exists an alternative method to achieve the desired outcome, or should I persist with refining and experimenting with the current approach?

Answer №1

It seems like you're aiming for a structure similar to this:

// Example data
const users = [
  { metadata: { creationTime: '3 apr' } },
  { metadata: { creationTime: '7 apr' } },
  { metadata: { creationTime: '26 jan' } },
  { metadata: { creationTime: '4 feb' } },
  { metadata: { creationTime: '9 dec' } },
  { metadata: { creationTime: '25 dec' } },
  { metadata: { creationTime: '9 apr' } }
]

// Lower-case month names... assuming creationTime is also in lower-case
const months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']

// Using `map` to create an array with counts for each month
const counts = months.map(month => {
  let count = 0
  
  // Looping through the `users` array using `of` instead of `in`
  for (const user of users) {
    // Using `includes` to check for month in creationTime
    if (user.metadata.creationTime.includes(month)) {
      ++count
    }
  }
  
  return count
})

console.log('Counts: ' + counts.join(' '))

In this case, the output is an array with counts for each month. You can modify the return value in the map function to return objects with month names and counts if that suits your needs better.

Your original code had a flaw with for (var month in months) {. This loop iterates over numeric indices instead of month names, resulting in checking for 0, 1, 2, etc. rather than jan, feb, mar, etc.. To iterate over the array contents, consider using a for/of loop instead.

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

Pause page scrolling temporarily in JavaScript while allowing the scrollbar to continue scrolling until the pause is lifted

I'm currently working on achieving a similar effect to the one found on this website: . On that site, as you scroll down, the 'HELLO' text moves to the side. I've managed to do that part successfully, but I'm facing an obstacle reg ...

Navigating a table while keeping headers in place at the top

Trying to construct a table where the thead remains fixed while the tbody scrolls. Utilizing percentages and fixed width for cell size determination, aiming for uniformity and alignment between percentage td's and thead headers. Referenced JSFiddle d ...

In Internet Explorer, the list items are overlapping, while functioning perfectly in all other web browsers

I've encountered a strange issue with my list item in Internet Explorer. Despite working perfectly in Chrome and other browsers, it fails to function properly in IE. I've built this application using the Vue framework and have faced various probl ...

Is it possible for Angular2 to map a lone JSON object?

Dealing with a JSON response that is a single object, rather than an array, can be tricky. Recently in my project, I encountered a situation where I needed to map and use such a response from an API to fill out a template. It seemed like a simple task at f ...

How come HTML components are able to immediately access the updated value of useState, even though it operates asynchronously?

Why does useState update immediately inside HTML codes but only on the next render in functions? import { useState } from 'react' function uniqueFunction() { const [data, setData] = useState('previous') function submit(e) { <-- ...

Inquiries about the jQuery Button Timer

Currently experimenting with jQuery to create a timer. Everything seems to be in place and the Stop Timer button is functioning properly. However, I'm facing issues with the Start Timer and Reset Timer buttons as they are not working as expected. Seek ...

Issue with hashtag in regular expressions

Looking for a way to identify and link hashtag words with an anchor tag? Here's a snippet showcasing the concept: <p class="display"></p> var content = "I enjoy #blueSky. My favorite color is #green. #sky is amazing"; ...

Working with MongoDB - Updating multiple subarrays within an array

Is it possible to delete elements from multiple subarrays within a single large array? The structure I'm working with is as follows: { "id": { "$oid": "" }, "users": [ { "friends": [ "751573404103999569" ] }, ...

Event triggered when a text input field becomes active (excluding onfocus) in the FireFox browser

I'm currently working on detecting when a text input field is active. Initially, I used the onfocus event, but I encountered an issue where the onblur event would be triggered when the window was no longer in focus, causing unintended consequences in ...

Retrieve the parseJSON method using a string identifier

I am trying to serialize a C# const class into name-value pairs, which I need to access by their string names on the client side. For example: return $.parseJSON(constantClass).property; This approach is not working as expected. Is there any alternative ...

Creating markers from Mysql database is a simple and efficient process

On my website, I have an array of markers that I use to display locations on a Google map. The array format I currently use is: generateMarkers([['Location', lat, long], ['Location2', lat2, long2],['Location3', lat3, long]3]) ...

Sharing package JSON file dependencies with child engines and addons in Ember.js

I am seeking information on how Ember Js can share the parent app's package.json file dependency (xyz:3.0.0) with child engines and addons without them needing to redeclare the dependencies in their own package.json files. This is to reduce the overal ...

Error message: An uncaught promise was encountered, despite adding a catch function. I am unable to identify the issue causing this error

Why is the added catch block not functioning properly? function maxRequest(url = ``, times = 3) { // closure function autoRetry (url, times) { console.log('times = ', times); times--; return new Promise((resolve, reject) => ...

The error message "invalid date" is appearing while trying to calculate the time difference with moment.js

I'm having trouble figuring out the time difference in hours and minutes between two form fields. I keep getting an error message saying "Invalid Date." I've attempted to modify other examples to fit my requirements, but without success. The inpu ...

Error: The function "execute" has not been declared

Hey there! I've created a Discord bot that is meant to check the status of a Minecraft server, but I'm encountering an issue with the embed. It's showing this error: UnhandledPromiseRejectionWarning: ReferenceError: execute is not defined. ...

No response headers retrieved from WebAPI

Currently, I am utilizing the ASP.NET WebApi in conjunction with a ReactJs application on the front end. In this scenario, I am working on implementing a Get method that enables file downloads from the server. My objective is to configure both the Content- ...

"Transforming a query into a JSON array - a step-by-step

My query generates the following output: { key:1,label:"R. Bulan"} { key:2,label:"R. Bintang"} { key:3,label:"R. Akasia"} { key:4,label:"R. Guest Room"} This is my SQL query: select '{ '||'key:'||IDMEETINGROOM||''||',l ...

An existing INPUT value can be modified by dynamically adding or subtracting values from SELECT OPTION

I currently have an <input readonly> field that displays the total_price value retrieved from a shopping cart stored in the database table. Moreover, I have included a <select> element with different transport options that can either increase o ...

Resetting md-radio-button choices within an Angular 2 application

My Angular app has a sorting filter using radio buttons via md-radio-group for users to choose how they want data displayed. The radio buttons work fine, but I'm struggling to clear them when the "Restore Defaults" button is clicked. This is the code ...

Animate the entire paragraph with CSS hover effect

I'm seeking ideas on how to achieve a specific effect without the need to wrap individual lines in inner elements like span or a. Check out this example <div class="m-linkitem"> <h1>Hover Below</h1> <a href="#">Lorem ...