Getting a particular year from a Date array in React is simple - you can use built

I am working with a dates array and need to implement a function that can filter out all the dates from either 2014 or 2015 depending on user input.

I attempted using substring() method, but it returned an array of the desired 2014 dates along with 2 undefined values. How can I modify my approach to get only the dates from 2014?

const datefunc = () => {
  const date = ['2014-4-4', '2014-5-4', '2015-4-4', '2015-3-4']

  const dates = date.filter((d) => {
    return d.substring(0, 4) === '2014';
  })

  console.log(dates)
}

datefunc()

Answer №1

Array.map processes each value in an array => when date.map is executed with the condition to only return dates starting with '2014', all other values in the array will be undefined.

Array.filter refines the elements in an array based on a condition => upon using date.filter, elements that do not meet the condition will be excluded from the resulting array.

To make your code work, you can update it like this:

const datefunc = () => {
  const date = ['2014-4-4', '2014-5-4', '2015-4-4', '2015-3-4'];

  const dates = date.filter((d) => d.substring(0, 4) === '2014');

  // Another option
  // const dates = date.filter((d) => d.startsWith('2014'));

  console.log(dates);
  
}

datefunc();

If your dates are not consistently formatted but valid date strings, you can convert them to Date objects and then filter them as follows:

const datefunc = () => {
  const date = ['2014-4-4', '2014-5-4', '2015-4-4', '2015-3-4'];

  const dates = date
    .map((d) => new Date(d))
    .filter((d) => d.getFullYear() === 2014);

  console.log(dates);
}

datefunc();

Answer №2

const dateFunction = () => {
  const datesArr = ['2014-4-4', '2014-5-4', '2015-4-4', '2015-3-4']

  const filteredDates = datesArr.filter((date) => date.substring(0, 4) === '2014')

  console.log(filteredDates)
}

dateFunction()

Answer №3

A more efficient approach would involve converting the string to a date format. It's also important to note that using the map method may not be suitable in this scenario as it doesn't handle filtering dates effectively. Even if no values are returned for false conditions, the result will still be undefined. This is why those undefined values are present.

const filterDates = () => {
  const datesArray = ['2014-4-4', '2014-5-4', '2015-4-4', '2015-3-4']
  const targetYears = [2014, 2015]; // Specify the years to filter on here
  const filteredDates = datesArray.filter((date) => {
    const currentYear = new Date(date).getFullYear();
    return targetYears.includes(currentYear);
  })

  console.log(filteredDates)
}

filterDates()

Answer №4

To select specific years, simply customize the filteredYears array as needed.

const datefunc = () => {
  const dates = ['2016-6-6', '2017-7-7', '2018-8-8', '2019-9-9']
  const filteredYears = [2017, 2018];
  const filteredDates = dates.filter(date => filteredYears.includes(new Date(date).getFullYear()));

  console.log(filteredDates)
}

datefunc()

Answer №5

One approach is to start by converting the datestring into a date type, and then utilize the "filter()" method to extract dates from a specific year. This process can help you achieve your desired outcome!

const dates = ["2014-4-4", "2014-5-4", "2015-4-4", "2015-3-4"];
let convertedDates = [];

function getYearList() {
    dates.forEach(date => {
      convertedDates.push(new Date(date));
    });

    convertedDates = convertedDates.filter(
      date => date.getFullYear() === 2014
    );
    console.log(convertedDates);
}

Answer №6

function filterDatesByYear(arr, yr) {
  return arr.filter((date) => date.includes(yr));
}

const datesArray = ["2020-4-10", "2020-5-15", "2021-2-28", "2021-3-20"];
console.log(filterDatesByYear(datesArray, "2020"));

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

Can Node.js be utilized to generate an XLS excel file while specifying the cell type?

I've noticed that many libraries have the capability to export to XLSX (Excel > 2007) or CSV formats, but not in XLS (which I assume is due to its outdated file format). I came across something where if you use fs.createOutputStream("filename. ...

tips for efficiently loading JSON files using Angular

I currently have a situation where multiple controllers are calling the method getData() from a service. To prevent unnecessary duplicate http calls for the same json file, I have implemented the following approach: QuizApp.service('quizService' ...

The debate between client-side and server-side video encoding

My knowledge on this topic is quite limited and my Google search didn't provide any clear answers. While reading through this article, the author mentions: In most video workflows, there is usually a transcoding server or serverless cloud function ...

How do I set up Firebase functions to trigger onWrite when listening for a specific child just once?

Is there a way to access the child under a different node each time the Firebase onWrite function is triggered? To retrieve this child, you can use the following code: {const saatt = (context.database.ref('kullanicilar/1111/marina1/2021/1saat'). ...

Having trouble with installing the most recent versions of React App dependencies

After cloning a project from GitHub, I attempted to install dependencies using npm install, but encountered an error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email ...

Is there a way to trigger jQuery animations even when the browser window is not in focus?

Hi there, I am currently working on developing an ajax-based multiplayer game that connects to a server for updates. The game has various game states and requires the GUI to be animated accordingly. However, I have encountered a problem where jquery anima ...

How can I use querySelector in JavaScript to target all div elements that have the same class?

I'm having an issue with the document.querySelector in my JavaScript code. It currently only selects the first div that contains the class "test", but I need it to select all such divs. Is there a way to achieve this using my existing JavaScript? ...

Images not showing in Vue.js

I have been working on setting up a carousel using bootstrap-vue. It is being generated dynamically through an array containing three objects with keys such as id, caption, text, and image path. The issue I am facing now is that while the caption and text ...

error in routing using koa-router with koa

I've been diving into learning Koa and trying out some basic exercises, but I'm having trouble implementing a simple routing feature. I followed the code from this tutorial and here's what I have so far: var koa = require('koa'); v ...

Determining the selected option's value made by the user

On my index.php file, which contains the form and function, I have the following code: $(function() { $.ajax({ type: "POST", url: "invtype.php", data: "getrevenuetype=true", success: function(b){ $("#revenue ...

What might be causing the hasOwnProperty(key) method in JSON to return false?

I have successfully implemented a method to loop through the JSON data provided below: {"dummmysetsJSONArr":[{"entryID":"1","distance":"100","calories":"50"},{"entryID":"2","distance":"200","calories":"100"},{"entryID":"3","distance":"300","calories":"150 ...

iOS device experiencing issue with resolving promise after attempting to signInWithEmailAndPassword using Ionic, Vue, and Firebase

I've been struggling with this issue for a while now and have reached a point where I am unable to find a solution on my own. Therefore, I have decided to reach out and ask for help by posting my own question. In my Ionic 7 Vue application, I am usin ...

What causes the 'find' query to return a Query object instead of the expected data in MongoDB?

After researching extensively on SO, I have yet to find a solution to my ongoing issue. Currently, I am in the process of developing a project using node, express, and mongodb. To start off, I created a seeder file to populate some data into mongodb: var ...

I encountered a "ReferenceError: db is not defined" while trying to call a function in Express.js with MongoDB intergr

The structure of the code is as follows: var express = require('express'); var router = express.Router(); var mongo = require('mongodb').MongoClient; function getData(){ db.collection("collection_name").find({}).toArray(function (er ...

Illumination scope for directional lights in three.js

In the world of three.js, calculating shadows for directional lights involves setting a range based on a bounding box that extends from the light source. This means that if I want to limit how far shadows are rendered, I need to adjust the bounding box geo ...

In JavaScript, using window["functionName"](arguments) will result in a TypeError message saying that the function does not exist

When trying to execute an AJAX function based on the active tab in my application, everything works smoothly when I trigger the function after specific events. However, I encounter difficulties when attempting to call the function using a dynamically gener ...

Troubleshooting issue with ng-click functionality in AngularJS within an <li> element

When creating a pagination list image with AngularJS, I encountered an issue where the ng-click directive was not working when used in either an <li> or <a> tag. However, it worked perfectly fine within a <button> tag. <div ng-control ...

Troubleshooting: Issue with Adobe Analytics DTM custom script property not being successfully

I'm attempting to display the most recent time I made changes and the current version of the library. Initially, I crafted a data element called Global - Example: return "DTM:" + _satellite.publishDate.split(" ")[0] + "|" + "Adobe:" + s.version; Su ...

The pop-up box triggered by Onbeforeunload will not be displayed

Currently, I am in the process of developing a website that includes user profiles. At this stage, I am focusing on the image upload functionality. When a user successfully uploads an image, it is stored in four different folders: one for size 25, 100, 150 ...

Choosing the right jQuery selector to target a section that contains div elements

Whenever the h2 element within a section is clicked, I want all the fields in that section to be displayed. For example, if the user clicks on 'Contact Information', the three form inputs (fields) below the Contact Information heading should appe ...