Pavel Karel
Pavel Karel

Reputation: 13

Matching arrays with strings

I would like to write simple script for displaying birthday and nameday congratulations. The goal is

1) Get curent day. 2) Store employes data in array. 3) If some employe name matches variable nameday, then write to document congratulation. Notice that on day, more names could celebrate namedays, then all employes must receive congratulation. 4) Same for birthday, more people can celebrate birthday at same day. 5) If name/date do not matches our employe list then do nothing.

I writed this

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

today = day +'. '+ month+'. '+ year;
dayMonth = day +'. '+ month+'.';

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


var nameday;
var age = employees - year;
var employeesName;

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


if (employees === nameday) {
  document.write("' + employeesName + ' and ' + employeesName + ' nameday today. Congratulation!")
}

if (dayMonth === nameday) {
  document.write("John Star is ' + age + ' tady and Mick Sinatra is ' + age + ' today. Congratulation!")
}

I know that the end of the code is wrong, but how can I get the right data from array? How can I acces to all first names and then match it with array?

codepen http://codepen.io/anon/pen/rrpRmG?editors=0012

Upvotes: 1

Views: 45

Answers (1)

user3297291
user3297291

Reputation: 23372

I'd transform your array of employees into an object that holds an array of employees for each day.

Then, you can get a list of employees that have their birthday by getting the date prop in this object!

Here's how it works:

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);

Upvotes: 1

Related Questions