Search code examples
javascriptarraysjsonjavascript-objects

Filtering Json File by Day and creates another Object


i'm trying to filter a JSON file with objects that have a property with Dates. I have it to filter this JSON, separate the content by a property that have a Date and by Day. After that i have to get this "parts" and filter again... but the most problem is to create this new agrouped by Day parts to filter again...

The code to examplify:

// this is the Data from the API just to simulate
const data =
   [
      { date: "10/01/2023", id: 1 , whatever: "hi" },
      { date: "01/02/2023", id: 2 , whatever: "hello"},
    ]

// this is the allDates filtered that i get before from the JSON with no nulls and no duplicates
const dtList = ["10/01/2023", "01/02/2023"];

so, for now i have this example, that i used before(that i found here) to filter dates by month, but it only works with months:

 var months = [
      "Jan",
      "Feb",
      "Mar",
      "Ap",
      "May",
      "Jun"
    ];
    var ordered = {};

// this data come from the api for example
    for (var i = 0, len = data.length; i < len; i++) {
      var entry = data[i];
      var m = entry.date.substring(0, 10);
      if (m !== "") {
        var mm = parseInt(m.split("/")[1]) - 1;
        if (!ordered[months[mm]]) {
          ordered[months[mm]] = [];
        }
        ordered[months[mm]].push(entry);
      }
    }

this code creates an object that contains all the data filtered and separated with the months, so after that i can do that:

//i filtered again with all the things i want and by date because ordered have subobjects separated by month...
  ordered.Jan?.forEach((obj) => {
      if (!isNaN(obj.nuParc)) {
        nuParcJun += obj.nuParc;
        setNuParcJun(nuParcJun);
      }

// this code have some react too

and i need to do the same thing but with days.

//i was trying something near to this, but with no results untill now
dtList.forEach((value) => {
      var dtsSep = Data.filter((obj) =>
        obj.date.includes(value)
      );
      var ordered = {};
      var ordered1 = Object.assign(ordered, dtsSep);
      

Solution

  • You have to parse the date string to an actual 'Date' object, then group the data and then perform your desired operation on each group like this:

    // Assuming `data` is your array of objects
    const data = [
      { date: "10/01/2023", id: 1, whatever: "hi" },
      { date: "01/02/2023", id: 2, whatever: "hello" },
    ];
    
    // Helper function to parse dates in DD/MM/YYYY format
    function parseDate(dateString) {
      const [day, month, year] = dateString.split('/');
      return new Date(year, month - 1, day); // Note: months are 0-based
    }
    
    // Group data by day
    const groupedByDay = data.reduce((acc, item) => {
      const date = parseDate(item.date);
      // Create a date string that includes the day for grouping
      const dayKey = date.toISOString().split('T')[0]; // Format: YYYY-MM-DD
    
      if (!acc[dayKey]) {
        acc[dayKey] = [];
      }
    
      acc[dayKey].push(item);
      return acc;
    }, {});
    
    console.log(groupedByDay);
    
    // Now you can filter or manipulate data for each day
    // Example: Iterate over each group and do something
    Object.keys(groupedByDay).forEach(day => {
      const items = groupedByDay[day];
      // Perform your operations on `items`, which are all the entries for this `day`
      console.log(`Processing items for day: ${day}`, items);
    
      // Example operation: filter items based on some condition and do something with them
      items.forEach(item => {
        // Example condition: item.id is even
        if (item.id % 2 === 0) {
          console.log(`Even ID found: ${item.id}`);
          // Perform your desired operation here
        }
      });
    });
    

    hope that helps ✌️