Arranging objects in clusters of 7 and 8 using javascript

Programming:

const fs = require("fs");
const { parse } = require("csv-parse");

function fetchSchedule() {
    let scheduleData = [];

    fs.createReadStream("./timetable.csv")
        .pipe(parse({ delimiter: ",", from_line: 2 }))
        .on("data", function (row) {
            let classCode = "ΘΗΨ3β";

            // Extracting relevant items for classes and storing them in a variable
            for (let i = 0; i < row.length; i++) {
                if (row[i].includes(classCode) || row[i].includes("ΓΘ2Φ5-3") || row[i].includes("ΓΘ1Μ7-3")) {
                    scheduleData.push({ number: i, text: row[i] });
                }
            }

            // Sorting the extracted items
            for (let i = 0; i < scheduleData.length; i++) {
                if (scheduleData[i + 1]) {
                    if (scheduleData[i].number > scheduleData[i + 1].number) {
                        let temp = scheduleData[i];

                        scheduleData[i] = scheduleData[i + 1];
                        scheduleData[i + 1] = temp;
                    }
                }
            }

            let numberOfObjects = 8 // <-- determines number of objects in each group

            // Grouping items into sets of 8
            let groupedItems = scheduleData.reduce((acc, elem, index) => {
                let rowNum = Math.floor(index / numberOfObjects) + 1;
                    acc[`${rowNum}`] = acc[`${rowNum}`] || [];
                    acc[`${rowNum}`].push(elem);
    
                    return acc
            }, {});

            console.log(groupedItems)
        });
}

fetchSchedule();

Desired Output Pattern:

{
  '1': [
    { number: 3, text: 'ΓΘ1Μ7-3 / 16 / Μαθηματικά...' },
    { number: 4, text: 'ΘΗΨ3β / 24 / Ψηφ.Ηλεκτρονικά II      Γ  ΘΗΥ' },
    ...
  ],
.....
  '5': [
    { number: 37, text: 'ΓΘ1Μ7-3 / 16 / Μαθηματικά...' },
    ...
  ]
}

The current issue is that there are consistently 8 elements in the first and fourth sets, while the second, third, and fifth have 7 items. I've attempted various solutions including conditional statements and adding empty elements between the last and first of each set but haven't succeeded.

Answer №1

const fs = require("fs");
const { parse } = require("csv-parse");

function calculateSchedule() {
    let timetable = [];

    fs.createReadStream("./timetable.csv")
        .pipe(parse({ delimiter: ",", from_line: 2 }))
        .on("data", function (row) {
            let focusClass = "ΘΗΨ3β";

            // Extract relevant items for student classes and store in a variable
            for (let i = 0; i < row.length; i++) {
                if (row[i].includes(focusClass) || row[i].includes("ΓΘ2Φ5-3") || row[i].includes("ΓΘ1Μ7-3") || row[i].includes("ΓΘ2Φ1-3")) {
                    timetable.push({ number: i, text: row[i] });
                }
            }

            // Sort the extracted items in ascending order
            for (let i = 0; i < timetable.length; i++) {
                if (timetable[i + 1]) {
                    if (timetable[i].number > timetable[i + 1].number) {
                        let temp = timetable[i];

                        timetable[i] = timetable[i + 1];
                        timetable[i + 1] = temp;
                    }
                }
            }

            // Group the items from timetable into groups of specified sizes
            let groupSizes = [8, 7, 7, 8, 7];
            let start = 0;
            let groupedResult = [];

            for (let size of groupSizes) {
                groupedResult.push(timetable.slice(start, start + size));
                start += size;
            }

            console.log(groupedResult)
        });
}

calculateSchedule();

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

I'm looking for a way to display a modal when a button is clicked and no record is selected from my table. My project is utilizing Bootstrap 4

<table id="resultTable" class="table table-hover table-bordered table-sm"> <thead> <tr> <th>Select</th> <th>Message Id</th> <th>Service</th> <th>Date</th> & ...

When the Popover appears in ShadCN, the input field unexpectedly takes focus

This unique component incorporates both Popover and Input functionality from shadcn. An issue I have encountered is that when I click on the Input to trigger the Popover, the Input loses focus and the cursor moves away from it. Expected outcome: Upon c ...

Leveraging Next.js ISR to pass extra information to the getStaticProps function from the getStaticPaths

Inside SingleBlogPost.jsx, the code for generating blog pages by their slug is as follows: export async function getStaticPaths() { const res = await fetch("http://localhost:1337/api/posts"); let { data } = await res.json(); const paths = data.map(( ...

Sending information from AngularJS to nodeJs/Sequelize

I am currently in the process of developing an e-commerce website using Node.js/Sequelize and AngularJS. For my project, I have organized it into 2 main folders: Client (which houses AngularJS starter files) https://i.stack.imgur.com/0vzsF.png Server ...

Tips for passing an object by value to an Angular2+ component

Imagine having a scenario where I create a component that takes a Foo instance and generates a form for editing. export class ChildComponent implements OnInit { @Input() foo : Foo; @Output() onChange : EventEmitter<Foo> = new EvenEmitter<Foo& ...

Issue with unapplied nullable type during export操作

I'm struggling to understand why my nullable type isn't being applied properly Here's an illustration interface Book { name: string; author: string; reference: string; category: string; } async function handleFetch<T>(endpoin ...

Dealing with CORS policy challenge

I am encountering an issue with Access to XMLHttpRequest at 'http://demo.equalinfotech.com/Iadiva/images/product/1634623781ladiva_barbara_01.glb' from origin 'http://localhost:8100' being blocked by CORS policy due to the absence of the ...

JQuery drag and drop functionality experiencing issues in Chrome Browser specifically when integrated into a Joomla Article

I recently embedded a jQuery drag and drop example into my Joomla article. Surprisingly, it works perfectly fine on Firefox browser but encounters issues on Chrome. Although the drag and drop functionality works on Chrome, the problem is that the buttons b ...

What is the best way to distinguish the compiled files from the source code, while still being able to test and view Express views directly from the source?

I am embarking on a new project using node. I have chosen to organize my directory structure by keeping all source files under ./src and the files intended for server upload under ./dist. The semi-complete directory layout is displayed below. Once built, t ...

Managing date validation for a three-part field using AngularJS

I am currently working on validating a three-part date field using AngularJS. I have managed to create a custom validation function, but I am struggling with determining how the fields should update each other's status. How can I ensure that all thre ...

What could be causing my dropdown links to malfunction on the desktop version?

I've been developing a responsive website and encountering an issue. In desktop view, the icon on the far right (known as "dropdown-btn") is supposed to activate a dropdown menu with contact links. However, for some unknown reason, the links are not f ...

Developing real-time chat functionality in React Native with node.js and Socket.io

I'm on the lookout for resources to help me navigate both server-side (mostly) and client-side development. I recently came across a resource called Simple Real Time chat app but unfortunately, it did not yield significant results. I tried locally ho ...

Tips for successfully sending data to an ng-include controller

So, I've got this ng-include html element, and I'm trying to figure out how to pass data from an external source to the controller. The primary controller is responsible for fetching json data from a http webservice, and then parsing that data i ...

Is it possible to utilize AND (&&) OR ( || ) operators within the dependency array of React JS?

Is it possible to include the && and/or || operators in the dependency array like this: const isVisible = true const isModified = false useEffect(() => console.log("both are true"), [isVisible && isModified]) Some may consider this to ...

Inquiry about Date and Time Selection Tool

I am working on a PHP project that includes two textboxes: one for selecting dates and the other for choosing a specific time. What I need assistance with is disabling any times before the selected date in the second timepicker textbox if today's dat ...

Is there a way to delete a field from a JSON object using JavaScript?

Searching for a way in Node.js to eliminate the date and operation fields from the database. Any suggestions on how to do this? Currently, all fields are being transferred to the FE. The collection pertains to MongoDB. collection.find({'recordType&ap ...

Using jQuery to dynamically add or remove table rows based on user inputs

Apologies if this is too elementary. I am attempting to insert rows into a table if the current number of rows is less than what the user requires. Simultaneously, I need to remove any excess rows if the current number exceeds the user's specificati ...

Tips for comparing strings that are nearly identical

Looking to filter elements from an array based on partial matching of a string. For example, trying to match PGVF.NonSubmit.Action with NonSubmit by checking if the string contains certain keywords. The current code is not functioning as expected and only ...

Guide to adding a Json file in a PHP file with PHP

I have a PHP file with an embedded JSON file, and I want to update the JSON file with new information from a form. The form looks like this: <form action="process.php" method="POST"> First name:<br> <input type="text" name="firstName"> ...