Pairing arrays to their corresponding strings

I am looking to create a simple script for displaying birthday and nameday congratulations. The objective is to:

  1. Retrieve the current day.
  2. Store employee data in an array.
  3. If an employee's name matches the nameday variable, display a congratulatory message for all employees celebrating namedays on that day.
  4. Repeat the same process for birthdays where multiple people can celebrate their birthdays on the same day.
  5. If a name or date does not match our employee list, take no action.

This is what I have written so far:


const today = new Date();
const day = today.getDate();
const month = today.getMonth() + 1;
const year = today.getFullYear();

const employees = [
  ["Frank", "Jagger", "6. 10.", "1984"],
  ["Ringo", "Lennon", "6. 10.", "1983"],
  ["John", "Star", "4. 10", "1962"],
  ["Mick", "Sinatra", "4. 10", "1961"]
];

let nameday;
let age;
let employeesName;

switch (dayMonth) {
  case "6. 10.": 
    nameday = "Frank, Ringo, Steve"; 
    break;
  default: 
    nameday = '';
}

if (employees.includes(nameday)) {
  document.write(`${employeesName} nameday today. Congratulations!`);
}

if (dayMonth === nameday) {
  document.write(`John Star is ${age} today and Mick Sinatra is ${age} today. Congratulations!`);
}

I understand that the end of the code needs modification. How can I access and compare all the first names in the array correctly?

View the codepen here.

Answer №1

I suggest reorganizing your array of employees into an object structure where each day holds a list of employees with birthdays on that specific day.

This way, you can easily retrieve the employees whose birthday falls on a particular date by accessing the corresponding property in the object!

Below is an example code snippet demonstrating how to achieve this:

var employees = [
  ["Test", "Person", "7. 10.", "1234"],
  ["Frank", "Jagger", "6. 10.", "1984"],
  ["Ringo", "Lennon", "6. 10.", "1983"],
  ["John", "Star", "4. 10", "1962"],
  ["Mick", "Sinatra", "4. 10", "1961"]
 ];

// Create birthday overview
var birthdayOverview = employees.reduce(function(obj, employee) {
  var birthday = employee[2];
  obj[birthday] = obj[birthday] || [];
  obj[birthday].push(employee);
  
  return obj;
}, {});

// Find today's birthdays:

var today = new Date();
var currentDay = today.getDate();
var currentMonth = today.getMonth() + 1;
var currentDateFormatted = currentDay +'. '+ currentMonth+'.';

var birthdayToday = birthdayOverview[currentDateFormatted];

console.log(birthdayToday);

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

Incorporating the outcome of an asynchronous function into my 'return' statement while iterating through an array

Issue I am Facing I encountered a problem while trying to execute a database function while simultaneously mapping an array. To illustrate this problem in a more concise manner, I have developed a sample code snippet. In my implementation, I am utilizing ...

Converting JSON data into an array using JavaScript

Stored in a variable named "response", I have the JSON value below: {"rsuccess":true,"errorMessage":" ","ec":null,"responseList":[{"id":2,"description":"user1"},{"id":1,"description”:"user2"}]} var users=response.responseList; var l = users.length; H ...

React Sortable JS is causing the bootstrap grid style to disappear

As I work on developing a straightforward React application, my goal is to integrate React Sortable Js into my Bootstrap grid layout. However, when I enclose within <ReactSortable>, the grid layout no longer displays two boxes side by side in two ro ...

When I utilize the three.js GLTFLoader to import a 3D model in GLTF format, I can't help but notice

As a beginner in frontend development, I lack knowledge of OpenGL. I am using the three.js GLTFLoader to import a 3D model, but the result is not satisfying. The preview on the model website looks ugly, and I want to improve the appearance to match the sam ...

Modifying an item within an array will not automatically result in an update to the corresponding HTML elements

When editing the object, it is done in JSON format, but only the previous data appears in the browser. To retrieve a list of products from local storage, I utilize these hooks: const Cart = () => { const [products, setProducts] = useState([]); c ...

I encountered Hydration errors while attempting to use dangerouslySetInnerHTML to render a script on my webpage

My current solution involves utilizing dangerouslySetInnerHTML as a final attempt, as my script fails to execute properly. The specific format is necessary for the plugin to display on the frontend; otherwise, the console reports that ImageMapPro is undefi ...

Conceal Reveal Secret Script

Can you help me with a question regarding the spoiler on this specific page? Here is the link: When I click on Windows, a table appears. However, when I click on Linux, the content of Windows disappears. I am looking to create a spoiler like this, but whe ...

What is the process for making changes to Google Sheet information?

Encountering an issue when trying to update data in a Google sheet using Next.js. The error message ReferenceError: row is not defined keeps popping up and I can't figure out where I'm going wrong. Any help in resolving this error would be greatl ...

Changing the CSS class of the Bootstrap datetime picker when selecting the year

Is there a way to change the CSS style of the Bootstrap datetime picker control so that when selecting years, the color changes from blue to red? I attempted to do this with the following code: .selectYear { background-color:red!important; } However ...

Discover how to implement custom data filtering in an Angular controller

Help needed: How can I remove decimals, add $ symbol in an Angular controller? Any ideas? $scope.data = [{ "key": " Logo", "color": "#004400", "values": [ [0, parseInt($scope.myappslogo)] ] }, { "k ...

What is the process for converting monthly data into an array?

I am working with an array of daily data that looks like this: var data = [{x: '2017-01-01', y: 100}, {x: '2017-01-02', y: 99}, /* entire year. */]; Each element in the array has an x field for date and a y field for a number. This ar ...

Are there any other benefits to utilizing the Decorator pattern besides enhancing dynamic behavior?

Currently, I am diving into the intricacies of the Decorator design pattern and a particular thought has been nagging at me. What if we simply had one base class with boolean values representing its features? Consider this example: Imagine a textview tha ...

Modify background color of a div depending on the text within the div

At this website, I have a unique "status tag" (such as Diesel, Auto, Manual, etc) displayed on each inventory picture. I am looking to dynamically change the background color of the tag based on the text within the DIV element. Below is the code snippet t ...

How can you calculate the ratio of one property value to another in AngularJS?

In my code, I am using ng-repeat to display data values from an object. <div ng-controller="myctrl"> <ul ng-repeat="number in numbers"> <li><span ng-bind="number.first"></span></li> <li><span ng-bind ...

Is there a way to provide a dynamic value for the p:remoteCommand ajax call?

My issue involves a p:dataTable that contains p:commandLink elements. I need to initiate an ajax call with parameters when the mouseover event occurs. After some research, it became clear that commandLink cannot trigger an ajax call on mouseover directly - ...

The utilization of 'new' is not allowed with an expression that does not have a call or construct signature in TypeScript

While searching for a solution, I stumbled upon this link which unfortunately did not provide the answer I was looking for: Cannot use 'new' with an expression whose type lacks a call or construct signature I am facing a similar issue. In my JavaS ...

Getting the checkbox count value in a treeview upon successful completion of an AJAX request

After successful JSON Ajax response, a treeview structure with checkboxes is displayed. I need to capture the number of checkboxes checked when the save button is clicked. @model MedeilMVC_CLOUD.Models.UserView <script type="text/javascript"> ...

the session data is being mishandled

I have integrated express-session and express-mysql-session in my application to handle sessions and store them in a MySQL database. The session data is saved in a table named "sessions". const express = require('express'); const session = requir ...

emptyQueue in jQuery

I'm currently working with a jQuery script that takes the src of an image, places it in a hidden div, and enlarges the image with an animation when hovering over the requested image. However, I've encountered an issue where the clearQueue or stop ...

Sorry, the variable you are trying to access has not been

I encountered an unexpected error: TypeError: slides[i] is undefined. It's puzzling because shouldn't the slides variable be accessible? <script> $('document').ready(function() { $.ajax({ type: "POST", ...