Discovering the variance among two arrays of dates in JavaScript

I am attempting to identify the variance between two sets of dates stored as arrays, and then segregate all distinct dates into a separate array for future use. Additionally, I have a specific functionality in mind. I have a variable called diffDates. It needs to be an array as it may contain indices of multiple months. Using this diffDates, I aim to populate selectDiffDates.

I welcome any suggestions to enhance and potentially optimize this code, as well as any ideas on implementing the aforementioned additional functionality. Thank you. Link to fiddle.

Array.prototype.diff = function(a) {
    return this.filter(function(i) {
        return (a.indexOf(i) < 0);
    });
}

var monthIndex = [0,1,2,3,4,5,6,7,8,9,10,11];
var dMarked=[], dFiltered=[], selectDiffDates = [];
dMarked=["Thu Jan 01 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Feb 05 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Mar 05 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Apr 02 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Jun 04 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Jan 01 2015 00:00:00 GMT+0500 (Pakistan Standard Time)"];

dFiltered=["Thu Jan 08 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Feb 12 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Mar 12 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Apr 09 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu May 07 2015 00:00:00 GMT+0500 (Pakistan Standard Time)",
 "Thu Jun 11 2015 00:00:00 GMT+0500 (Pakistan Standard Time)"];

var dMarkedMonths = [], dFilteredMonths = [];
for(var i=0; i<dMarked.length; i++){
 dMarkedMonths.push( monthIndex[new Date(dMarked[i]).getMonth()]);   
}
for(var i=0; i<dFiltered.length; i++){
 dFilteredMonths.push( monthIndex[new Date(dFiltered[i]).getMonth()]);   
}

console.log(dMarkedMonths);
console.log(dFilteredMonths);
var diffDates = dFilteredMonths.diff( dMarkedMonths );

console.log("Difference: "+diffDates);

for(var d=0; d<dFiltered.length; d++){
    if(new Date(dFiltered[d]).getMonth() == diffDates){
     selectDiffDates.push(dFiltered[d]);   
    }
}
console.log(selectDiffDates);
$("#console").html(selectDiffDates);

Answer №1

diffDates is actually an array, so the correct approach is to check if the desired month exists within the diffDates array:

for(var d=0; d<dFiltered.length; d++){
    if(diffDates.indexOf(new Date(dFiltered[d]).getMonth())>-1){
     selectDiffDates.push(dFiltered[d]);   
    }
}

Regarding performance, please refer to the updated fiddle at http://jsfiddle.net/q7rmr5uq/3/

Your current approach does not align with the specified requirement. It currently selects months, finds different ones, and then generates dates based on the obtained months. This method overlooks dates with the same month but different day or year.

A more suitable approach for your requirement should involve calculating the difference between two dates rather than focusing solely on two months.

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

Find any consecutive lowercase or uppercase letter and include one more

I have a task in Javascript that I need help with. The goal is to insert a special character between a lowercase and uppercase letter when they are matched together. For example: myHouse => my_House aRandomString => a_Random_String And so on... T ...

Choosing and Duplicating Text in Angular

I'm attempting to give the user the ability to select a paragraph and copy it by clicking a button. However, my current code is not working as expected. I initially tried importing directives but encountered errors, prompting me to try a different met ...

Use Jackson to populate a Plain Old Java Object with an array from the main JSON node

Utilizing Jackson and RESTEasy for integration with an external API has been successful in populating simple objects into POJOs. However, a challenge arises when receiving an array of objects as a response. [ { "variable1": "someValue1", "variab ...

Utilizing information shared between parent and child classes to plot points on a globe

Working on an exciting project to enhance my ReactJS and ThreeJS knowledge, I encountered an issue with passing data from the parent class to functions in the child class. Here's a glimpse of my project: App.js import React, {Component} from 'rea ...

What is the best way to sort through data retrieved by a server component in a NextJS 13 AppDir?

I've hit a roadblock trying to integrate a search bar that filters server-fetched data in my project using NextJS 13 and AppDir. Despite numerous attempts, I can't seem to get it right. It feels like there's something crucial I'm overlo ...

Parcel JS: The function tree.render is missing or not defined

Every time I attempt to execute the production build command npm run build or npx parcel build index.html, this error occurs. My project consists of simple HTML and CSS, without any React or third-party libraries. What could be causing this issue? I have t ...

Running the gulp uncss command with regex to ignore specific elements is not functioning as expected

I have been attempting to integrate uncss into my gulp workflow. In order to exclude certain classes, such as those added through javascript, I am specifying these classes with "ignore" (specifically, I am trying to remove the css from the jquery plugin m ...

Storing a variable in an array in a separate file: A step-by-step guide

What I have tried: To tackle this issue, I began by creating a new file named links.js, inside which is a single array. In my main file (index.js), the program scrapes URLs. The goal is to save these URLs in the specified format within the links.js file ...

How to display the total of specific values on the screen using React

Looking to create an app that displays 9 boxes, each with 4 select options: close successful, close unsuccessful, callback, and open. The goal is to count the number of closed successful and unsuccessful boxes and display the total count at the top of the ...

Guide to efficiently utilizing flex to horizontally position two elements next to each other in a Material UI and ReactJS environment

I have successfully achieved side-by-side components of two cards from Material-UI. However, I am facing an issue when expanding one of the cards. The problem is that Card 1 automatically expands to match the size of Card 2 when Card 2 is expanded, even th ...

Tips for creating a dynamic menu with animated effects

Check out my fiddle here: http://jsfiddle.net/k3AHM/23/ $(document).scroll(function () { var y = $(this).scrollTop(); if (y > 110) { $('.menu-container').addClass( "fix-menu" ).animate('top', '-3px&a ...

Monitor the fullscreenChange event with angularJs

Utilizing a button to activate fullscreen mode for a DOM element using the fullscreen API is functioning correctly. The challenge arises when exiting fullscreen mode, requiring the listening for the fullscreen change event in order to resize the DOM elemen ...

In C#, create a list of arrays with a set size

I have a function that works with pixel data. My goal is to create a single list containing RGB values, but when I try declaring it like this: List<int[]> maskPixels = new List<int[3]>(); An error occurs: Array size cannot be specified in ...

Highest Positioned jQuery Mobile Section

Requesting something a bit out of the ordinary, I understand. I currently have a jQueryMobile page set up with simplicity: <div data-role="page" class="type-home" id="home"> <div data-role="header" data-theme="b"> <h1>Our To ...

Transmitting an array to JSON in PHP

These arrays need to be converted into JSON format: { "1JzSZFs2DQke2B3S4pBxaNaMzzVZaG4Cqh": 100000000, "12Cf6nCcRtKERh9cQm3Z29c9MWvQuFSxvT": 1500000000, "1dice6YgEVBf88erBFra9BHf6ZMoyvG88": 200000000 } Struggling to achieve this in PHP, a ...

Is there a way to include an image in a serialized file?

What is the method to include image_form into form in Django? form - form.serialize() image_form - image $('#id_submit').click(function(e) { e.preventDefault(); var form = $('form').serialize(); image_form = $("#id_image")[0].f ...

Tips for clearing input fields in React.js without using an empty string

Is there a way to reset the input field in this specific scenario? const [username, setUsername] = useState({ username: "", usernameError: "" }); const handleUsername = (inputUsername) => { if (inputUsername.length > ...

Mobile browser experiences video freezing when src is set through useState, yet it starts playing when triggered by a button click or when the video is set to M

Hey awesome folks at the StackOverflow Community, I'm currently encountering a perplexing issue with a video element in my web application. The video is supposed to play automatically on both desktop and mobile browsers. However, I've run into a ...

The positioning of the Material Ui popover is incorrect

I am currently working on a web application project with React and have implemented Material UI for the navbar. On mobile devices, there is a 'show more' icon on the right side. However, when I click on it, the popover opens on the left side disp ...

What is preventing me from successfully retrieving data at times when using curl_setopt and jQuery Ajax?

In my quest to fetch data from another server, I am using the curl_setopt PHP function along with Ajax. The function I have created seems to be working fine, but sometimes when I refresh the page and the internet connection is slow, I don't receive an ...