Tips on using the map and filter methods to narrow down a nested array based on specific object

I am struggling to filter JSON data based on a specific date using Array.Filter and Map. The code I have tried below is not yielding the desired results. Can someone please provide guidance on how to effectively filter JSON data based on a particular date using filter and map functions?

I am encountering difficulties in comparing the date filter value within the availabilities objects in my code.

Below is the code snippet that I have added:

let cruiseFilterData = [{
      "name":"text--1",
      "availabilities":{
         "2019":{
            "year":"2019",
            "items":[
               {
                  "discount":{
                     "name":"one"
                    },
                  "dateDepart":"12\/10\/2019"
                },
               {
                  "discount":{
                     "name":"Two"
                  },
                  "dateDepart":"15\/12\/2019"
                }
            ]
         }
      },
      "sort":0,
      "featured":true
   },
   {
      "name":"text--2",
      "availabilities":{
         "2019":{
            "year":"2019",
            "items":[
               {
                  "discount":{
                     "name":"one"
                    },
                  "dateDepart":"18\/05\/2019"
                },
               {
                  "discount":{
                     "name":"two"
                  },
                  "dateDepart":"12\/10\/2019"
               }
            ]
         }
      },
      "sort":1,
      "featured":true
   },
   {
      "name":"text--3",
      "availabilities":{
         "2019":{
            "year":"2019",
            "items":[
               {
                  "discount":{
                     "name":"one"
                  },
                  "dateDepart":"25\/05\/2019"
                },
               {
                  "discount":{
                     "name":"two"
                  },
                  "dateDepart":"12\/10\/2019"
               }
            ]
         }
      },
      "sort":2,
       "featured":true
   },
    {
      "name":"text--4",
      "availabilities":null,
      "sort":2,
       "featured":true
   }
]

let compareDate = 'Sat Oct 12 2019 00:00:00 GMT+0400 (Mauritius Standard Time)';

const linkedItinerary = cruiseFilterData.map((element) => {
    element.availabilities = Object.keys(element.availabilities).filter((value, index) => {
        element.availabilities[value].items.filter((value, index) => {
            const dateValue = value.dateDepart;
            if (dateValue.indexOf('/') >= 0) {
                const dateSplit = dateValue.split(' ')[0];
                const parts = dateSplit.split('/');
                let propDate;
                if (parts) {
                    const dateMerge = '' + parts[1] + '/' + parts[0] + '/' + parts[2];
                    propDate = new Date(dateMerge);
                } else {
                    propDate = new Date(dateValue);
                }
            }
            if(propDate.toDateString() === new Date(compareDate).toDateString()) {
                return value;
            }
        });
        return value;
    });
    return element;
});

console.log(linkedItinerary);

Answer №1

It seems that there is some uncertainty regarding the goal you are trying to achieve. If your objective is to filter the available cruise options based on the user's selected date (represented by the variable compareDate), you can modify your code as follows:

    let cruiseFilterData = [{
          "name":"text--1",
          "availabilities":{
             "2019":{
                "year":"2019",
                "items":[
                   {
                      "discount":{
                         "name":"one"
                        },
                      "dateDepart":"12/10/2019"
                    },
                   {
                      "discount":{
                         "name":"Two"
                      },
                      "dateDepart":"15/12/2019"
                    }
                ]
             }
          },
          "sort":0,
          "featured":true
       },
       {
          "name":"text--2",
          "availabilities":{
             "2019":{
                "year":"2019",
                "items":[
                   {
                      "discount":{
                         "name":"one"
                        },
                      "dateDepart":"18/05/2019"
                    },
                   {
                      "discount":{
                         "name":"two"
                      },
                      "dateDepart":"12/10/2019"
                   }
                ]
             }
          },
          "sort":1,
          "featured":true
       },
       {
          "name":"text--3",
          "availabilities":{
             "2019":{
                "year":"2019",
                "items":[
                   {
                      "discount":{
                         "name":"one"
                      },
                      "dateDepart":"25/05/2019"
                    },
                   {
                      "discount":{
                         "name":"two"
                      },
                      "dateDepart":"12/10/2019"
                   }
                ]
             }
          },
          "sort":2,
           "featured":true
       },
        {
          "name":"text--4",
          "availabilities":null,
          "sort":2,
           "featured":true
       }
    ]
    
    let compareDate = new Date(2019, 12, 15); // Year, month, day.
    
    let linkedItinery = cruiseFilterData.filter((cruise) => {
        // Exclude all cruises without any availabilities
        if(!cruise.availabilities) return false;
        // Check if the current cruise has at least one availability for the selected date
        return Object.values(cruise.availabilities).findIndex(availability => {
           return availability.items.findIndex((item) => {
              // First, we split the date by /
              const [day, month, year] = item.dateDepart.split('/');
              // We create a new date
              const dateValue = new Date(year, month, day);
              // Compare both dates to check if they are the same
              return dateValue.getTime() === compareDate.getTime();
           }) !== -1;
        }) !== -1; // -1 means not found. Using findIndex here stops the loop as soon as it finds a matching element, avoiding unnecessary iterations
    });
    
    console.log(linkedItinery);

First, I changed your compareDate variable to a pure Date object.

Then, I filtered the original list based on nested criteria. The goal is to find cruisers with availabilities and check if at least one date matches the user input within those availabilities.


Please let me know if this is not what you expected, and I will adjust my code according to your clarification.

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 function .play() cannot be executed on document.getElementById(...) - it is not a

There is an error in the console indicating that document.getElementById(...).play is not a valid function. import React from 'react'; const musicComponent=(props)=>{ const style={background:props.color} return( <div classN ...

Troubleshooting ng-click not functioning within ng-repeat with database integration in MEAN Stack

//app.js var blogApp = angular.module('BlogApp', []); blogApp.controller('BlogController', function($scope, $http){ $scope.createPost = createPost; $scope.deletePost = deletePost; function init(){ getAllPosts(); } init(); ...

Newest Angular package.json

Each time I attempt to update my Angular components to the latest version, I encounter the same error. It seems like a never-ending cycle... npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/ ...

Execute the CountUp function when the element becomes visible

Currently, I am implementing the following library: https://github.com/inorganik/ngx-countUp Is there a way to activate the counting animation only when the section of numbers is reached? In other words, can the count be triggered (<h1 [countUp]="345 ...

The TypeScript error message states that a value of 'undefined' cannot be assigned to a type that expects either a boolean, Connection

I've been grappling with this code snippet for a while now. It was originally written in JavaScript a few months back, but recently I decided to delve into TypeScript. However, I'm struggling to understand how data types are properly defined in T ...

Angular - Set value only if property is present

Check if the 'rowData' property exists and assign a value. Can we approach it like this? if(this.tableObj.hasOwnProperty('rowData')) { this.tableObj.rowData = this.defVal.rowData; } I encountered an error when attempting this, specif ...

I'd like some clarification on the code that dynamically adds routes using Typescript and Node Express. Can someone please

Running my API server with node/typescript and express / express validator, I came across this code that I found really useful for separating route logic: function createCustomRouter(route: Array<CustomRouteEntry>): Router { const customRouter = R ...

What could be causing the radio button to not be checked when the true condition is met in Angular?

I am working on an angular7 application that includes a dropdown list with radio buttons for each item. However, I am facing an issue where the radio button is not checked by default on successful conditions. Below is the code snippet from my component.htm ...

A straightforward method of transmitting data from JavaScript to the Python back-end within a Streamlit application

Utilizing the st.components.v1.iframe, I integrated an authentication system that sends a token back to the parent when a user is authenticated. The iframe content is as follows: <script src="remote/auth.js"></script> <scri ...

Unable to access Session state in Web Service through ajax on the client side

I'm facing an issue where the system is generating a new session for each user when I run an ajax query, instead of having just 1 session per user. Strangely, there were no issues when I tested it in debug mode on my computer, but problems arose on th ...

Extracting Node.js data within a Node.js script

Can a node.js file be parsed to execute part of the code within another node.js file? I am attempting to parse a node.js file from within a different script. I do not have control over the contents of the file, but it always contains a function called get ...

What exactly is the purpose of editing a host file?

After reviewing this repository, an automatic message pops up: Don't forget to modify your host file 127.0.0.1 * http://localhost:3001 What exactly does that entail? ...

The function rowSelected was triggered twice, once for being selected and once for being deselected

Utilizing Ag-Grid in my grid has been smooth sailing so far, but now I find myself needing to implement a click event on a row under certain conditions (error condition callback). The desired functionality is such that upon the first click on a row, it beh ...

Saving changes to mesh vertices in r67 of Three.js

I've encountered an issue with saving a mesh to a text file after manipulating vertices in my plane model. While the rendering on screen works as expected, the updates are not reflected in the saved file. Interestingly, if I move a vertex before the ...

Encountering a CORS issue while attempting to make a GET request to an API in an

Looking to retrieve HTML data from a website using an API. The target URL is: https://www.linkedin.com/ Trying to fetch the HTML page as text from this specific URL. Here's what I attempted: getData() { const api = "https://www.linkedin. ...

Inquiry regarding delays in updating and retrieving data with Mongoose in Node.js

I recently faced an issue related to the CRUD development process. Whenever I update a property and check the response in Postman, it always shows the previous data. For instance, after clicking send on Postman, it shows "weeks" : "11" instead of "10". Che ...

The Google APIs sheet API is throwing an error message stating "Invalid grant: account not found"

I need to retrieve data from a spreadsheet using the Sheet API. After setting up a project in Google Cloud Platform and creating a service account, I granted the account permission to edit the spreadsheet. I then downloaded the credentials in JSON format. ...

What could be causing the image file input to appear sideways or flipped?

I am currently working on a Vuejs component that allows users to select a file from their local system. Once the user selects an image, it is previewed in a div. However, I have noticed that some images appear 'flipped' sideways automatically, es ...

Is there a way to print messages to the console of openDevTools in Electron JS?

After finishing a hello world application using electron js, I have successfully printed to my terminal with console.log and opened the openDevTools in the window of my application. However, I am now interested in finding a way for my console.log stateme ...

The functionality of jQuery.hover with AJAX is malfunctioning

I am facing an issue with my jquery hover combined with $.post method. My initial intention was to create a series of select buttons where hovering would trigger a change in the image being displayed (the image path would be loaded via $.post). The image ...