Filtering an array results in an empty output

My task involves iterating through multiple date intervals, like:

  1. 09/06/2023 - 15/06/2023
  2. 28/05/2023 - 02/06/2023
  3. 17/06/2023 - 18/06/2023
  4. 29/06/203 - 04/07/2023 ...and so on

I want to extract the day numbers for a specific month only, for example, June (06).

The expected output should be an array like this:

var june = [09,10,11,12,13,14,15,01,02,17,18,29,30];

To achieve this, I followed these steps:

a. Queried in PHP to retrieve departing, returning dates, and number of date intervals as string arrays (not Date objects)

b. Created JavaScript arrays for departing, returning dates: var departure, var rback, var number

c. Defined an empty array 'days':

var days=[];

d. Looped through all date intervals to obtain dates between the intervals

function enumerateDaysBetweenDates(startDate, endDate) {
        startDate = moment(startDate,"DD/MM/YYYY");
        endDate = moment(endDate,"DD/MM/YYYY");
    
        var now = startDate, dates = [];
    
        while (now.isBefore(endDate) || now.isSame(endDate)) {
            dates.push(now.format("DD/MM/YYYY"));
            now.add(1, 'days');
        }
        return dates;
    };

for (i = 0; i < number.length; i++) {
    
    var mdepart=departure[i];
    var mrback=rback[i];
    
    
    
    days.push(enumerateDaysBetweenDates(mdepart,mrback));
    
    };

Next step is to filter out dates that are not in June:

function checkd(num) {
  return num.includes("/06/");
};
 
var june=days.filter(checkd);

The issue I encountered is "days.filter is not a function" error...

If I try using

var june = Object.values(days).filter(checkd);
, it results in an empty array...

I'm unsure about the problem. Is it because the initial date array elements were defined as strings and now they are treated as dates with moment.js?

Complete code snippet:

var days=[];
var number=[1,2,3,4];
var departure=[09/06/2023,28/05/2023, 17/06/2023, 29/06/2023];
var rback=[15/06/2023,02/06/2023,18/06/2023,04/07/2023];

function enumerateDaysBetweenDates(startDate, endDate) {
        startDate = moment(startDate,"DD/MM/YYYY");
        endDate = moment(endDate,"DD/MM/YYYY");
    
        var now = startDate, dates = [];
    
        while (now.isBefore(endDate) || now.isSame(endDate)) {
            dates.push(now.format("DD/MM/YYYY"));
            now.add(1, 'days');
        }
        return dates;
    };

for (i = 0; i < number.length; i++) {
    
    var mdepart=departure[i];
    var mrback=rback[i];
    
    
    
    days.push(enumerateDaysBetweenDates(mdepart,mrback));
    
    };

//Now I need to filter all dates that are not in June:

function checkd(num) {
  return num.includes("/06/");
};
 
var june=days.filter(checkd);

//Error days.filter or empty array....
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Answer №1

By consistently formatting the date strings as dd/mm/yyyy, you can utilize various array methods like Array#filter to extract all the dates falling in June:

const data = [
  '09/06/2023 - 15/06/2023',
  '28/05/2023 - 02/06/2023',
  '17/06/2023 - 18/06/2023',
  '29/06/2023 - 04/07/2023'
],

searchMo = '06',

searchDays = data.flatMap(
    range => range.split(' - ')
    .filter(date => date.split('/')[1] === searchMo)
    .map(date => date.split('/')[0])
);


console.log( searchDays );

Answer №2

If you're looking to streamline your date/time handling in JavaScript, consider swapping Moment for Luxon. The syntax may differ slightly, but Luxon's immutability and recommendations make it a solid choice. Developed by the same team as Moment, it offers a reliable alternative.

For an in-depth look at various JavaScript date/time libraries, check out this informative post:

JavaScript format date / time

To manage days within a specific month effectively, converting raw data into date ranges can simplify the process. By iterating through these ranges and adjusting start dates until they match end dates, you can achieve the desired outcome.

Keep in mind that I utilize month indexes rather than numeric representations of months. JavaScript's built-in Date object references months by their indexes, which you may wish to modify for consistency.

Note that no year considerations are included in the code snippet, assuming all dates fall within the same year.

const { DateTime } = luxon;

const data = [
  '09/06/2023 - 15/06/2023',
  '28/05/2023 - 02/06/2023',
  '17/06/2023 - 18/06/2023',
  '29/06/2023 - 04/07/2023'
];

const dateFormat = 'dd/MM/yyyy';

const parseDate = (timestamp, format) =>
  DateTime.fromFormat(timestamp, format); // Luxon parse

const ranges = data.map(item =>
  item
    .split(/\s*-\s*/)
    .map(timestamp => parseDate(timestamp, dateFormat)));

const daysInMonth = (ranges, monthIndex) => {
  const days = new Set();
  let currDate;
  for (let [startDate, endDate] of ranges) {
    currDate = startDate;
    while (currDate <= endDate) {
      if (currDate.month - 1 === monthIndex) {
        days.add(currDate.day);
      }
      currDate = currDate.plus({ days: 1 }); // Increment to next day
    }
  }
  return [...days]; // Could also call: .toSorted((a, b) => a - b)
}

const days = daysInMonth(ranges, 5); // June is the 5th index

console.log(...days); // 9 10 11 12 13 14 15 1 2 17 18 29 30
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.3.0/luxon.min.js"></script>

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 animation when the mouse leaves the screen

After searching through various resources, I couldn't find a definitive solution to my issue. The problem I am facing is that when the .mouseenter(function(){ }) function is triggered, and immediately followed by the .mouseleave(function(){ }) functio ...

Guide on setting the focus of an input in a form field using ngIf

I am currently facing an issue where I need to focus on a specific input in my code based on certain conditions derived from an observable. In this scenario, I have initialized a boolean to true inside the ngOnInit() method. export class InputOverviewExamp ...

The ES6 reduce method is not giving the expected result

In Image 1, the output you will see if you log the final array from Snippet 1. My goal is to transform my array to match the format shown in Image 2. I attempted using lodash's _.uniqBy() method [Snippet 2], but the logged output of the reduce varia ...

What is the process for sending a post request in the inline editor of Dialogflow?

Currently, I am utilizing the blaze tier, so there should be no billing concerns. I have also added "request" : "*" in my package.json dependencies. Check out my code index.js below: ` 'use strict'; var global_request = require('requ ...

Ways to change the chart type in ApexCharts

I'm seeking a way to change the chart type of an existing ApexCharts that has already been rendered. After reviewing the methods, I attempted to use the updateOptions() method, but encountered the error: Uncaught TypeError: Cannot read property &apos ...

Vue - Utilizing mapState in Vuex to display the contents of the first object within an array

I am trying to display the names array from the first object in players using mapState with Vuex. Currently, the objects in players are listed based on their titles, but I want to filter them based only on the names in the first object for the current page ...

The DELETE function in express.js with MySQL integration is encountering a problem where it is unable to

As I work on setting up my website, the backend utilizes express.js to send queries to a MySQL Database. However, when attempting to delete rows, no action seems to take place. function establishConnection() { return mysql.createConnection({ multipl ...

Arranging and moving list elements without the use of jQuery UI (or any jQuery libraries at all?)

I have been searching for a JavaScript plugin that offers the same functionality as jQuery UI Sortable, which is the ability to drag and drop items to reorder them. In my case, these items are <li> tags. I prefer not to use jQuery UI because it is h ...

Utilizing the jQuery plugin 'cookie' to retain the current tab selection on a webpage

Is it possible to provide a detailed explanation on how I can utilize the jQuery Cookie plugin to maintain the selected tab throughout my entire website? Here is the current JavaScript code in JSFiddle format: http://jsfiddle.net/mcgarriers/RXkyC/ Even i ...

How can we delete a specific word from a string if it is found in an

Facing a seemingly simple problem that's proving tricky to solve. I have an array of product names and a sentence. The goal is to remove any product names from the sentence if they appear in it. const products = ["premium t-shirt", "t-shirt", "swea ...

Collapse the sidebar using React when clicked

Just beginning to learn about React and I'm trying to figure out how to toggle the open/closed state of a react-pro-sidebar component using a click event: export default function MaterialLayout(props) { const { children } = props; const classes = us ...

Remove multiple HTML rows based on checkbox selection

At first, a table is generated with 5 rows. Now the goal is to remove all rows where the checkbox is checked. This is achieved by adding a checkbox in cell[0] and using a delete button that loops through all rows to delete the selected ones. The process w ...

ASP updatePanels causing scrollable grid plugin offsetWidth to be undefined

I am attempting to create scrollable gridviews within update panels by utilizing a function that is called in the pageLoad() function LoadScrollPopupOverridesBehavior() { $('.GridViewPopupWithOverride').Scrollable({ ScrollHeight: 350 ...

Is there a way to create animated CSS box-shadow depth using jQuery or CSS3 transitions?

This code snippet applies delays but doesn't seem to update the style changes until the loop completes: for (i=20;i>=0;i--) { var boxShadow = i+"px "+i+"px "+i+"px #888"; $('article').css("box-shadow", boxShadow); ...

What is the best way to conceal an element in a loop using React?

I'm facing an issue with this short React code where I'm trying to hide the header that corresponds to a button when that button is clicked. I want only the specific header and button to disappear within the loop. How can I achieve this? For exa ...

Understanding the scope of Javascript variables in mongoose queries

I am currently working on a project utilizing node.js, mongoose, and the Foursquare API. foursquare.getVenues(params, function(err, venues) { if(err) return res.json(JSON.stringify({status: 'error', returnData: err})); ...

I am in need of granting administrator privileges to enable image uploads for an online store built with React and Next.js

Currently, I am in the process of developing an e-commerce website utilizing NextJs. One of my objectives is to grant admin privileges where an admin can upload a product image that will be showcased on the dashboard along with the rest of the product deta ...

How can one optimize the speed of an image swap using jQuery or JavaScript?

I seem to have encountered a peculiar issue. In my code, I have the following snippet: http://jsfiddle.net/PMnmw/2/ Interestingly, in the jsfiddle example everything runs smoothly. The image swaps occur swiftly and effortlessly. However, when implemented ...

*Efficient ways to eliminate the limit parameter from the URL while using express-paginate.*

I am in the process of implementing paging with the express-paginate module. However, I am encountering an issue where the limit parameter is showing up in the URL like this: http://example.com:3010/feeds?page=2&limit=10. My preference is to eliminate ...

Experiencing delays with Angular 4 CLI's speed when running ng serve and making updates

After running ng serve, I noticed that the load time is at 34946 ms, which seems pretty slow and is impacting our team's performance. Additionally, when we update our code, it takes too long to reload the page. https://i.sstatic.net/lpTrr.png My Ang ...