Breaking up an array of objects into separate arrays based on a specific key using JavaScript

Context: Seeking assistance in developing a timetable planner that can detect time clashes. Any guidance or support is greatly appreciated.

Specific Issue: Struggling to determine how to divide my array of objects into multiple arrays with a specific key repeated.

The dataset at hand:

let myCourses = [
  {
    course: "ee3001",
    slots: [
      {
        day: "monday",
        time: "0900-1100",
      },
      {
        day: "tuesday",
        time: "0930-1100",
      },
      {
        day: "wednesday",
        time: "1330-1530",
      },
    ],
  },
  {
    course: "ee3002",
    slots: [
      {
        day: "monday",
        time: "0900-1100",
      },
      {
        day: "thursday",
        time: "0930-1130",
      },
    ],
  },
  {
    course: "ee3003",
    slots: [
      {
        day: "tuesday",
        time: "0930-1100",
      },
      {
        day: "wednesday",
        time: "1330-1530",
      },
      {
        day: "thursday",
        time: "0930-1130",
      },
    ],
  },
];

Arrays I aim to divide it into:

let newarray = [
  {
    course: "ee3001",
    slot: {
      day: "monday",
      time: "0900-1100",
    },
  },
  {
    course: "ee3001",
    slot: {
      day: "monday",
      time: "1300-1400",
    },
  },
  ...
  ...
];

let newArray2 = // containing information on ee3002
let newArray3 = // containing information on ee3003 

**Note:** The dataset should be dynamic, allowing users to input additional courses and timings.

  1. The rationale behind this division is so that I can utilize the Cartesian Product of arrays to identify all possible combinations.
  2. This will enable me to verify if there are any overlapping times within a given combination.
  3. Is there an improved method to address this issue?

Answer №1

Using the map method, I am able to iterate through the array and within that iteration, I utilize another map method to loop through the slots.

 let myCourses = [
      {
        course: "ee3001",
        slots: [
          {
            day: "monday",
            time: "0900-1100",
          },
          {
            day: "tuesday",
            time: "0930-1100",
          },
          {
            day: "wednesday",
            time: "1330-1530",
          },
        ],
      },
      {
        course: "ee3002",
        slots: [
          {
            day: "monday",
            time: "0900-1100",
          },
          {
            day: "thursday",
            time: "0930-1130",
          },
        ],
      },
      {
        course: "ee3003",
        slots: [
          {
            day: "tuesday",
            time: "0930-1100",
          },
          {
            day: "wednesday",
            time: "1330-1530",
          },
          {
            day: "thursday",
            time: "0930-1130",
          },
        ],
      },
    ];
    
    const newArray=[]
    myCourses.forEach(myFunction);

    function myFunction(item, index) {
      newArray[index] = [];
      item.slots.map((child) =>
        newArray[index].push({ course: item.course, slots: child })
      );
    }

Answer №2

Hello there, feel free to experiment with this sample:

let myCourses = [
      {
        course: "ee3001",
        slots: [
          {
            day: "monday",
            time: "0900-1100",
          },
          {
            day: "tuesday",
            time: "0930-1100",
          },
          {
            day: "wednesday",
            time: "1330-1530",
          },
        ],
      },
      {
        course: "ee3002",
        slots: [
          {
            day: "monday",
            time: "0900-1100",
          },
          {
            day: "thursday",
            time: "0930-1130",
          },
        ],
      },
      {
        course: "ee3003",
        slots: [
          {
            day: "tuesday",
            time: "0930-1100",
          },
          {
            day: "wednesday",
            time: "1330-1530",
          },
          {
            day: "thursday",
            time: "0930-1130",
          },
        ],
      },
    ];
    let Arrayee3001 = [];
    let array1 = myCourses.filter(course => course.course === "ee3001")
    array1[0].slots.forEach(slot => {
       let result = {};
       result.course = array1[0].course;
       result.slot = [];
       result.slot.push(slot);
       Arrayee3001.push(result);
    });
    
    console.log(Arrayee3001);

In this code snippet, I have specifically filtered the myCourses array by the course ID. Afterward, for each slot within the filtered array, an object named result is created containing the course obtained from the filtered array and the current slot. These objects are then stored in a final array named Arrayee3001.

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

Filtering out banned terms in a PHP string

I am currently facing a challenge with my Javascript code that dynamically generates an XML string. Once this string is sent to a PHP file, I need to ensure that it does not contain any malicious words that could potentially lead to SQL injection attacks. ...

Add elements to an array with express, Node.js, and MongoDB

I'm currently learning about the MERN stack and I'm working on creating users with empty queues to store telephone numbers in E.164 format. My goal is to add and remove these numbers from the queue (type: Array) based on API requests. However, I ...

Bootstrap 4 modal experiencing issues with the form end tag functionality

Currently, I am facing an issue while attempting to incorporate a confirmation delete feature using a Bootstrap 4 modal in my Laravel project. The problem arises when the modal is opened, and the submit button fails to function. Upon inspecting the browser ...

Deleting list element from a function in bash

How can I delete an element from a list within a function? What's the reason behind push_list working as intended but not pop_list? #!/bin/bash declare -a item_list=() add_item() { item_list[${#item_list[@]}]="`echo $@`" } remov ...

Injecting CSS styles into a webpage using a Chrome extension before the page has completely loaded to achieve instant customization

As a newcomer to creating Chrome (or other browser) extensions, I am working on developing one that applies custom CSS rules to specific page elements. Overall, it seems to be functioning as intended, but with some minor issues. One issue I have encounter ...

Adjust the slide count accordingly when navigating to a particular item within the Bootstrap 3 Carousel

I made adjustments to the standard Bootstrap 3 Carousel so that it can navigate to a specific slide when the URL matches #. Although this feature is working, I am facing an issue with my pager-text not updating correctly when jumping to a specific slide. T ...

Place the child DIV at the bottom of its parent DIV

I've searched through open questions but couldn't find a solution. The code snippet in question looks like this: ... <div style="some height"> <div style="some width"> .......and so on.. .. < ...

Express Node fails to launch

I recently decided to try my hand at Express and learn more about it. However, I encountered an issue while trying to start a server. Initially, I attempted to access 127.0.0.1:8080 through Express but nothing seemed to be happening. Although I copied most ...

Unexpected Issue Encountered in JQuery Integration

I recently added jQuery to my HTML file: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> After that, I included a link to my JavaScript file: <script src="public/javascripts/new_javascript.js" type ...

The performance of aframe is being affected by the use of bounding boxes for collision

Hey there! I recently created a component to handle collision detection for primitive and non-primitive shapes. While using the bounding box collision feature provided in three.js, everything was working smoothly. However, when applying it to custom object ...

The function grunt.task.run() is malfunctioning

Currently, I am experimenting with integrating Grunt into my Express application. Here is a snippet of the code I have: var grunt = require('grunt'); require(process.cwd() + '/gruntfile.js')(grunt); grunt.task.run('development&ap ...

Having trouble with the automatic closing feature of Bootstrap drop down in React?

While using the drop button feature of Bootstrap, I have encountered a situation where it works fine when clicked on, but disabling it by clicking outside using autoClose='outside' does not seem to work as expected. When I click on my hamburge ...

Guide on redirecting a webpage post form validation in JavaScript

I have a question about my JavaScript code. Even if validation fails, the contact us page still appears. How can I fix this issue? Appreciate any help. Thank you! (function () { window.addEventListener('load', function () { var forms = do ...

Issue: Unable to 'locate' or 'access' ./lib/React folder while utilizing webpack

I've been delving into the world of React for a while now and decided to experiment with integrating it with webpack. Below is my webpack.config.js : var path = require('path'); module.exports = { entry: './app.js', outp ...

jQuery: Track mouse movement with a delay

I'm looking to create a div that follows cursor movement with a slight delay, similar to the effect seen on this website: In the example link provided, you can observe that the 'follower' has a brief delay in its animation. I attempted to ...

Move the navigation bullets of the Nivo Slider to the bottom instead of below the slider

Currently working on a website and have incorporated Nivo Slider to develop a jQuery slider. Encountering an issue with the bullets that indicate which slide the user is currently viewing. I'd like these bullets to be displayed on the images within t ...

Extract and preserve elements from an ordered array by segregating them into separate arrays of objects using Angular 8

I have an array called arrayReceived containing 15 objects. My goal is to sort and store the first 6 objects with the lowest amount value in a new array called arraySorted. These objects are sorted based on their amount parameter. There may be multiple obj ...

Adjust the language code in a URL using JavaScript or Node.js

Within my common header file, there is a navbar that includes a multilanguage dropdown menu. The issue I am facing is that when I select a language from the dropdown, the page translates correctly. However, when I navigate to other pages, the selected lang ...

How to set a canvas as the background of a div element

Check out my code snippet below: <!DOCTYPE html> <html> <body> <div id='rect' style='width:200px;height:200px;border:1px solid red'> </div> <canvas id="myCanvas" style="borde ...

Having trouble parsing JSON with Ajax in Pusher using PHP?

I am facing an issue while sending multiple parameters using the Pusher AJAX PHP library. This is the error I encounter: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data Here is my PHP and JS code: <script src="https: ...