Analyzing dates and compiling a count using JavaScript

In my current project, I am faced with the challenge of comparing dates stored in the format 'Y-M-D H-i-s' within an array to eliminate duplicates and keep a count alongside the original date. The method I am using to compare the dates is shown below:

function compare(a, b){
            if(a.getDate() == b.getDate() && a.getMonth() == b.getMonth() && a.getFullYear() == b.getFullYear()){
                return true;
            }else{
                return false;
            };
        };

Here is how I iterate through the dates in the array:

    times.forEach(function(timeOne){
        times.forEach(function(timeTwo){
            if(compare(timeOne, timeTwo)){
                console.log("same");
            }else{
                console.log("different");
                count.push(timeOne);
            };
        });
    });

Unfortunately, the above approach is not working as expected. It removes the first 1619 values without populating the count array, ultimately causing my browser to crash. I am seeking advice on how to resolve this issue or perhaps an alternative method to achieve the desired outcome. Additionally, I am uncertain about how to incorporate the count feature at this point.

Edit ---

Below is the code snippet remaining in the program:

var results = <?php echo $results; ?>,
            times = [],
            count = [];
     results.forEach(function(result){
         times.push(new Date(result.time));
     });

Lastly, it's important to note that the items array contains close to 30,000 entries. Therefore, I am looking for an optimized solution that can significantly reduce processing time.

Answer №1

Here are some helpful tips that may resolve your issue.

First, you can simplify your code to the following:

function compare(a, b){
    return a.getDate() == b.getDate() && a.getMonth() == b.getMonth() && a.getFullYear() == b.getFullYear();
};

Secondly, there is an error in your loop where the inner loop should be looping the j variable instead of i:

for(var j = 0; j < times.length-1; i++){
        ...
};

Thirdly, in order to remove duplicates, it's important to skip elements where i equals j since they will always be equal. Add the following line to the inner loop:

if(i == j) continue;

Fourthly, your current approach is incorrect. Pushing to the count array if an element is not the same as another element does not guarantee no duplicates. To properly search for duplicates within the array, follow this algorithm:

for(var i = 0; i < times.length; i++){
    if(times[i] == null || times[i] == undefined) continue;
    if(!contains(count, times[i])){
        count.push(times[i]);
    }
}

function contains(arr, elm){
    for(var i = 0; i < arr.length; i++){
        if(compare(elm, arr[i]))
            return true;
    }
    return false;
}

The count array should now contain only one instance of each date without any duplicates.

AFTER EDIT:

Dealing with 30000 entries requires a different approach. Try the solution provided and see if it works for you, but keep in mind that it might not be suitable for such a large dataset.

Answer №2

const compareArray = (times) => {
    for(let i = 0; i < times.length-1; i++){
        for(let j = 0; j < times.length-1; i++){
            if((i!=j) && times[i] && times[j]){
                if(compare(times[i], times[j])){
                    console.log("same!!!");
                }else{
                    console.log("not same!");
                    count.push(times[i]);
                };
            };
        };
    };
};

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 controller's AngularJS function seems to be unresponsive

Issue with AngularJs ng-click Event I'm attempting to utilize the GitHub Search-API. When a user clicks the button, my Controller should trigger a search query on GitHub. Here is my code: HTML: <head> <script src="js/AngularJS/angula ...

What is the best way to interpret varbinary data from SQL as a string using C#?

Currently, I am working on a web application that retrieves varbinary data from SQL and converts it into a byte array in the code using ExecuteScalar. Now, I am creating a Windows application version of this project where I want to bypass the DB connecti ...

Avoid displaying dates in chartjs that do not have corresponding values

I have a chart where some dates on the x-axis have no values, and I would like to exclude them. Below is an image of my chart: View my current chart Here is the code snippet for the options in my Chart JS: var options = { resp ...

Utilizing a Textarea for populating an Array with content

I am interested in creating a program that can extract the value from a textarea and use it to generate an array. Typically, an array is created as follows: <script type="text/javascript"> var numbers = [1,2,3,4,5]; </script However, I woul ...

A method for conditionally looping to match header rows with data rows in a map

When dealing with two types of rows: header rows and data rows, each consisting of 18 columns. The number of data rows is determined by the number of header rows, for example: If there are 2 header rows, there should be (2 data rows: first one maps to th ...

What are some recommended security measures for JSON data?

During my exploration of the topic of JSON vs XML, I stumbled upon this particular question. One of the arguments in favor of JSON was its ease of conversion in Javascript, specifically using the eval() function. However, this raised some security concerns ...

Utilizing useRef with React Three in App component results in null value for threejs entities

I'm encountering an issue with ref values while developing my threejs app in react. Typically, when we use useRef on any element, it returns the exact object after the first render. However, when working with threejs objects such as mesh or perspectiv ...

manipulating arrays in Python

Struggling to make the self.value work without errors, aiming to loop through self.a, self.b, self.c. Seeking help in learning how to achieve desired output x = [AA, EE, II] using classes and loops. Attempted a for loop but still new to Python and object ...

Choosing unique and shared elements within arrays using a PHP function

What is the optimal approach for this task? Consider having 2 arrays as input: $current = array('strawberry', 'apple', 'banana', 'peach'); $new = array('apple', 'blackberry', 'mango', & ...

Learning to retrieve and save information from an external file and assigning them as variables in JavaScript using three.js

As a newcomer to three.js, I'm still figuring things out and may be treading familiar ground with this query. Here's the situation: I've got an external .txt file that lays out the x, y, z positions for 256 atoms. The opening lines of said . ...

Typescript error: The property 'set' is not found on type '{}'

Below is the code snippet from my store.tsx file: let store = {}; const globalStore = {}; globalStore.set = (key: string, value: string) => { store = { ...store, [key]: value }; } globalStore.get = (key) => { return store[key]; } export d ...

Searching for information in one array using a loop with another array (MongoDB and JavaScript)

I have two arrays that need to be compared for matching elements. let firstArray = [1, 2, 3] let secondArray = [{id:1}, {id:1}, {id:3}] I am trying to create a new array containing objects with the same id. Despite trying different approaches, I am unabl ...

Under specific circumstances, two combo boxes will function with the jQuery select plugin

I am working on an ASP.NET MVC Razor view that contains two dropdowns. <select id="country_id" ... /> and <select id="city_id" ... /> When an option is selected in the country dropdown (country_id), the second dropdown (city_id) is populate ...

detect and handle errors when deploying the Node.js function

I'm currently attempting to use code I found on Github to insert data into a Firestore database, but unfortunately, I keep encountering an error. Here's the specific error message: 21:1 error Expected catch() or return promise/catch-or-re ...

Failure to update HTML with AJAX request

I am currently working on a form that calculates shipping costs based on the user's postcode input. The process involves retrieving the user's text input of the postcode, fetching the shipping cost for that specific postcode using PHP, and then u ...

What is the best way to transfer state information from a hook to be displayed in the App component in React

Is there a way to transfer the state(data) of info to the App hook, in order to showcase the properties within div elements? The function setInfo(info) saves the data intended for display on the Map hook and inspecting console.log(info) within _onClick rev ...

Guide on utilizing vue-router and router-link for managing links that are dynamically generated within jquery modules like datatables

I spent some time trying to "integrate" datatables.net (https://datatables.net/) into a Vue app. After some trial and error, I came across advice suggesting not a direct integration approach, but rather utilizing jquery modules as they are and "hooking" t ...

"Troubleshooting issue with jQuery failing to identify PHP variable within an if

I have managed to implement a code that utilizes jQuery and PHP session to add items to the cart. Everything is working smoothly except for displaying the status of the action, such as "Added to cart" or "Updated". The message about the status is stored in ...

What are the steps to showcase StreetViewPanorama within a React application?

Is it possible to have a fully working streetview using google API key? I've come across some libraries online, but their documentation seems poor or outdated. I attempted to use the @react-google-maps/api library with documentation available at . Ho ...

The Laravel route is guiding me to a different destination

Currently, I am facing an issue while trying to develop a CRUD application using Laravel and vue.js. Every time I launch the application, it redirects me to the dashboard but the CRUD functionalities are not visible. Below are the codes from Routes/web.a ...