Determine if the date of birth in JavaScript is within the last 110 years

I am dealing with an array of dates that looks like this:

var dateArray = ["1965-12-29", "1902-11-04", "1933-10-21", "1983-10-16"];

My goal is to check and calculate each date of birth element to determine if the age is less than 110 years old based solely on the year. If the age is greater than 110 years (based only on the year), then I want to remove/delete that element from the dateArray.

In essence, I am trying to replicate the following SQL query in JavaScript:

FROM TABLE X
WHERE TO_CHAR(DOB, 'YYYY') > (TO_CHAR(TO_DATE('2014/09/30', 'YYYY/MM/DD'), 'YYYY') - 110)

Thank you very much.

Answer №1

Try utilizing the `.getFullYear()` method found in the Date type:

for(var i=0;i<dateArray.length;i++)
{
   var now = new Date();// you can also specify a specific date like new Date("2014/10/15");
   var birth = new Date(dateArray[i]);
   var age = now.getFullYear() - birth.getFullYear();
   // then compare the age variable to see if it exceeds 110
}

This code should get the job done.

Answer №2

My approach to this problem would be as follows:

var dateArray = ["1965-12-29", "1902-11-04", "1933-10-21", "1983-10-16"];
dateArray = removeOldPeople(dateArray);

function removeOldPeople(dateArray){ 
    //Iterating backwards to remove items from array during iteration
    for(var i = dateArray.length -1 ; i >=0 ; i--){
      var dateString = dateArray[i].split("-");
      var year = dateString[0];
      var month = parseInt(dateString[1])-1;
      var day = dateString[2];
      var age = calculateAge(day, month, year);
        if(age >= 110) {
            dateArray =  dateArray.splice(i);
        }
    }
}

function calculateAge(birthMonth, birthDay, birthYear){
  todayDate = new Date();
  todayYear = todayDate.getFullYear();
  todayMonth = todayDate.getMonth();
  todayDay = todayDate.getDate();
  age = todayYear - birthYear; 

  if (todayMonth < birthMonth - 1){
    age--;
  }

  if (birthMonth - 1 == todayMonth && todayDay < birthDay){
    age--;
  }
  return age;
}

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

The "as" property in NextJS Link does not properly reload the page when opened

I recently started using NextJS and I have a question about its router. I want to link to a page, but I would like the URL to be different. <Link href="/About/About" as="/about-page"> <a> Who We Are <im ...

The JavaScript event responsible for reloading the page is triggering every time the page is refreshed, resulting in an endless loop

Initially, the issue does not arise, however, it only occurs when the event is triggered by reordering the column, causing an automatic reload afterwards. tabelaProdutos.on('column-reorder', function(e, settings, details) { ... location ...

Adding external data to an ng-repeat scope in AngularJS

Encountering a problem with AngularJS ng-view and ng-repeat, specifically related to managing the scope. Using ng-repeat to display a list of items from an array, with a button outside the ng-repeat scope triggering an array update on ng-click. However, un ...

Convert CSV into an object with additional attribute

I'm attempting to import data from a CSV file into a d3 tree graph. While I've successfully loaded the JSON version of the data, the d3.csv parser isn't returning the expected string. Some approaches I've tried include: treeData.forEa ...

I'm having trouble getting jQuery to work properly with Bootstrap buttons

In simple terms, my objective is to have two buttons on a page where "1" is displayed when the first button is pressed and "2" is displayed when the second button is pressed. This functionality works fine with radio inputs, but when I incorporate button la ...

"Does anyone know of a specific jQuery function that allows for mapping a collection, where the `end`

I have a query that searches for specific elements within a selected area: $(some_selector_here).find("ul li.active a span") I am looking for a function that can loop through this collection of elements and provide access to the complete stack of base el ...

What is the reasoning behind CoffeeScript automatically adding a function when extending an Object?

I'm currently working on a helper method to identify the intersection of two hashes/Objects in this manner... Object::intersect = (obj)-> t = {} t[k] = @[k] for k of obj t x = { a: 1, b: 2, c: 3 } w = { a: true, b: 3 } x.intersect(w) #=> ...

Retrieving data from a multidimensional array in an AJAX response using jQuery

When I use ajax to send data, the response I receive is a multidimensional array. $.ajax({ type: "POST", url: "/slideshow/list.php", data: imageId, success: function(data){ imagesList ...

Configuring multiple views directories in Express fails to function as expected

Looking to define multiple views directories in Express. Working with Express version 4.16.3, Node.js version v10.15, and EJS version 2.5.9. app.set('views', [path.join(__dirname, 'views'), path.join(__dirname, 'public/static/&apo ...

What is the best way to retrieve the full image path in a React component using the `<input>` file element and then save it to the local state?

Creating a basic shopping app using react, react-router, and bootstrap has been an exciting project for me. One of the features in my app is a form where I can add new products to the database. In this form, I can input details such as the product name, d ...

Guide on building a Vue Js input name field with string-variable schema

I have a project using VueJs and I am looking to extract JavaScript variables to create hidden fields. My goal is to set the name of the field based on the index of the variable, following a zig-zag naming schema. For example: <input type="text" nam ...

Using jQuery to revert back to the original SRC after mouse is not hovering over an element

I've been working on a script to change the src attribute for an icon. The icon I'm loading is a different color and it's meant to notify the user about the link associated with it. Currently, I have the src changing to the second icon on h ...

Is it possible for JavaScript to only work within the <script> tags and not in a separate .js

I'm facing a puzzling issue with my JavaScript code. It runs fine when placed directly within <script>...code...</script> tags, but refuses to work when linked from an external file like this: <SCRIPT SRC="http://website.com/download/o ...

Guide to creating a toggle button

Can someone help me create a button that toggles between displaying block and display none when clicked? I've been trying to use Classlist.toggle with JavaScript, but I'm not sure if I have the correct classes targeted. let showCart = documen ...

Utilize the power of RxJS to send numerous post requests within an Angular application

I have a form where users input names and count numbers. My goal is to append the number to each name. For example, If a user enters "worker" and a count of 5, I want to add numbers from 1 to 5: worker-1, worker-2, worker-3, worker-4, worker-5. After cr ...

How to specify a unique body parser for a specific route in Express

Currently, I am utilizing express version 4 in my project. Within my server.js file, I have integrated the express.json() middleware to handle JSON data. require('dotenv').config(); const express = require('express'); const cors = requi ...

Automating the process of running npm start on page load: A guide

Recently, I've been delving into learning npm in order to incorporate it into a website. I'm curious about how exactly it is used within a website - do you typically need to execute the command "npm start"? How does this integration work for a li ...

A guide on utilizing a function import within an exported function within ReactJS

As a beginner in React, I have been exploring Named and Default Exports, but I encountered a problem that I am having trouble articulating. Below is the code that is causing confusion: namedExport.js const name = "xyz"; const age = 20; const my ...

A lone function making two separate calls using AJAX

I have a function that includes two Ajax Get calls. Each call has a different function for handling success. function get_power_mgt_settings() { window.mv.do_ajax_call('GET',power_mgt.get_spin_down_url{},'xml',true,show ...

Refresh tab controllers in Angular JS on every click event

Is there a way to refresh the tab controller every time a tab is clicked? Here's the current code: $scope.tabs = [ { id: 'tab1', title: 'tab1', icon: 'comments', templateUrl: 'tab1/tab1.tpl.html&ap ...