Generating intricate arrays from a given list

If I have an array containing various items like the following:

[
    ["Core", "Mathematics", "Mathematics 20-4"],
    ["Core", "Mathematics", "Mathematics 30-1"],
    ["Other", "Fine Arts", "Art", "some art course"],
    ["Other", "Fine Arts", "Music", "some music course"],
    ["Other", "Forensics", "some forensics course"],
    ["French Immersion", "Core", "Mathématiques", "Mathématiques 30-1"]
]

The structure being "Department -> Subject -> Course".

I am looking to generate a dynamic Array (or Object) in the format below (or any other logical structure)...

{
    subjects: [
        {
            title: "Mathematics", courses: [ "Mathematics 20-4", "Mathematics 30-1" ]
        },
        {
            title: "Mathématiques", lang: "fr", courses: [ "Mathématiques 30-1" ]
        }
    ],
    other: {
        subjects: [
            {
                title: "Forensics", courses: [ "some forensics course" ]
            },
            {
                title: "Fine Arts", subjects: [
                    {
                        title: "Art", courses: [ "some art course" ]
                    },
                    {
                        title: "Music", courses: [ "some music course" ]
                    }
                ]
            }
        ]
    }
}

The "Other" department does not strictly adhere to the "Subject -> Course" hierarchy and can vary with "Subject -> Subject -> Course" and "Subject -> Course". Introducing a type attribute such as "course" or "subject" may be helpful, but maintaining a hierarchical structure is preferred.

I have been struggling to dynamically convert this into an Array or Object structure.

Answer №1

let classes = {};
for(let i = 0; i < arr.length; i++){
   let department = arr[i][0];
   let subject = arr[i][1];
   let course = arr[i][2];
   classes[department] = classes[department] || {};
   classes[department][subject] =  classes[department][subject] || [];
   classes[department][subject].push(course);
}

This code snippet will create an object structured like this:

classes = {
   core:{
     mathematics:["math1", "math2"],
     english: ["english1,"english2"]
   }
  Other:{
    "Fine Arts":[...],
    "Forensics":[...]
  }

}

If you want to access an array of courses for a specific subject, you can do so by using the following syntax:

let courseList = classes[<department>][<subject>];

Answer №2

After being inspired by @ben336, @user1787152 and checking out the discussion on DevShed forum thread, I developed the following code:

var Department,
    departments = [];

Department = function(title) {
    this.title = title;
    this.subjects = [];
};

function parseTitles( titles )
{
    var i, department, departmentTitle,
        hasDepartment = false;

    departmentTitle = titles.shift();

    for (i=0; i<departments.length; i++) {
        if (departments[i].title === departmentTitle) {
            hasDepartment = true;
            break;
        }
    }

    if (!hasDepartment) {
        department = new Department(departmentTitle);
        departments.push(department);
    }

    departments[i].subjects = titles;
}

The subjects are used for navigation purposes, with courses retrieved via JSON queries. Subjects are stored in an Array format, allowing for querying JSON data for courses when the last subject is clicked.

I aim to acknowledge @ben336 for providing the initial answer and give credit where it's due.

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

What is the process for inserting a scroll bar within a div element?

   I have recently created a webpage using some divs, along with a bit of CSS and JavaScript. I am struggling to figure out how to add a scrollbar to one of my divs. The code is not overly complex, as it includes both CSS and JavaScript. <html> & ...

Guide on verifying the accessibility of individual directories within a file path in Unix/Bash

A Text File Contains Paths on Each Line. Directories Need to be Created from the Paths. This Can be Achieved Easily Using Commands like mkdir -p is/isapp/ip/ipapp. However, the Issue Arises When Access Permissions are Only Changed for the Final Directory ...

Searching for a specific collection item based on a custom property (excluding _id) in Meteor - what's the best approach?

I am facing an issue with my application that utilizes Flow Router along with its pub/sub functionality. I have set up a collection and template helpers. The code works fine on the client side. Template.theCase.helpers({ theCase: function () { ...

Error encountered: Attempting to use a class as a function in vue-socket.io is not permitted

I am developing a Vue chrome extension where I am attempting to implement web sockets using vue-socket.io. I have followed the basic instructions on deploying a node server with express and socket.io on Heroku, but I am encountering issues with the conne ...

The elimination function in JavaScript

I've been browsing the Mozilla Developers website, focusing on the concept of the delete operator. In the final section about "Deleting array elements," there are two similar scripts presented, with the only difference being how they modify the array. ...

Should Errors be Handled in the Service Layer or the Controller in the MVC Model?

Currently, I am in the process of developing a Backend using Express and following the MVC Model. However, I am uncertain about where to handle errors effectively. I have integrated express-async-errors and http-errors, allowing me to throw Errors anywher ...

Different ways to resize an image in various sizes without relying on PHP thumb

I have developed an admin panel for managing reservations of charter, yacht and other vehicles. I am looking for a solution to upload only one image per vehicle and resize it in multiple sizes without relying on the phpthumb library due to its slow loadi ...

Achieving left alignment for Material-UI Radio buttons: Float them left

Click here to view the demo https://i.stack.imgur.com/Yt4ya.png Check out the demo above to see the code in action. I'm currently struggling to align the radio buttons horizontally, wondering if there's an easier way to achieve this using Mater ...

Encountering a Issue in Transmitting Data from Laravel Controller to Ajax using Jquery GET Method with

Currently, I am utilizing Laravel 5.4 as the Backend server technology. Below is the Controller code snippet from my Backend: $locations = Neighborhood::where('House_id', $id)->get(); $json = json_encode($locations); return respon ...

Ways to retrieve the chosen option in a dropdown list without specifying the dropdown's name, id,

Custom dropdown, Model-View-Controller Code @foreach (var attribute in Model) { string controlId = string.Format("product_attribute_{0}_{1}_{2}", attribute.ProductId, attribute.ProductAttributeId, attribute.Id); @switch (attribute.AttributeControl ...

Searching for and replacing text that spans across multiple nodes in HTML can be accomplished using C# programming language

Here is the HTML code to consider. The term 'response' was modified to 'reason', by removing 'sp' (<del> tag) and adding 'as' (<ins> tag), while also removing 'se' (<del> tag). <div &g ...

Does it have .hasOwnProperty and a significant value?

Today, I encountered a tricky situation involving the JavaScript Object.hasOwnProperty method. I was working on a form that creates properties on an object. The issue arose when dealing with a select box that had a value selected and then reset back to it ...

Error 404: This page seems to have gone missing. Django and react-router

Struggling to integrate reactjs and react-router (1.x) with my Django project. I'm finding it challenging to make everything work together seamlessly. For more details, you can check out the project on GitHub: https://github.com/liondancer/django-che ...

Sequelize makes it easy to input records into various tables simultaneously

Embarking on my first experience with Sequelize and MySQL, I am seeking guidance on inserting data into two tables with a foreign key relationship. Let's delve into the structure of the entities - bookingDescription and bookingSummary. //bookingSumma ...

Encountering an issue while attempting to replicate the Spotify app on localhost:3000. The error message "TYPEERROR: Cannot read property 'url' of undefined" is hind

As a first-time user of stackoverflow, I am unfamiliar with its rules and regulations, so I apologize in advance for any mistakes I may make. Currently, I am attempting to create a Spotify clone using React. Everything was going smoothly until I completed ...

"Switching Classes with a Click Event: A Step-by-

This script is designed to work with SoundCloud's widget in order to enable remote text buttons. I am attempting to modify it so that it functions as a remote for an image button that toggles between different pictures for pause and play, rather than ...

Retrieve data from a server using an Ajax GET request to access information stored within an HTML

Seeking guidance on implementing a jQuery GET request for retrieving specific information from a page structured similar to the following: <tr class='tr'> <td class='example1'> <span> Information I possess ...

Tips on saving an array as a variable

Can anyone help me figure out how to store a PHP variable into a JavaScript variable? var myArray; function retrieveData(id) { $.post( "main/updater.php", { id:id } ).done(function( data ) { myArray = data; }); } I&ap ...

Include the button beneath the Rating section using JQuery or AJAX

I am having trouble adding buttons after the result.date in my code. Placing the buttons between td tags is causing an [object Object] error to show up. $.ajax({ type: 'GET', url: 'someUrl.php', data: {op : "demo"}, da ...

Remove the innerHTML content of dynamically added elements using jQuery

After researching, it seems that event handlers are commonly added using methods such as .live(), .on(), .bind(), or .delegate(). My previous question may not have been clear, so I decided to delete it and ask a simpler one. Is there a way to clear the in ...