Verify the presence of the item within the array that is nested

I have the following JSON data

const data = {
    rooms: [
        {
            roomId: 1,
            schedules: [
                { home1: "06:00", dayOfWeek: 1, away: "21:30" },
                { home1: "06:05", dayOfWeek: 2, away: "22:30" }
            ]
        },
        {
            roomId: 2,
            schedules: [
                { home1: "06:00", dayOfWeek: 4, away: "21:30" },
                { home1: "06:05", dayOfWeek: 5, away: "22:30" }
            ]
        }
    ]
}

My goal is to add elements for the missing dayOfWeek within the schedules array of both rooms.

This is the desired output:

const finalOutput = [
    //for room 1
    { home1: "00:00", dayOfWeek: 3, away: "02:30", roomId: 1 },
    { home1: "00:00", dayOfWeek: 4, away: "02:30", roomId: 1 },
    { home1: "00:00", dayOfWeek: 5, away: "02:30", roomId: 1 },
    { home1: "00:00", dayOfWeek: 6, away: "02:30", roomId: 1 },
    { home1: "00:00", dayOfWeek: 7, away: "02:30", roomId: 1 },
    //for room 2
    { home1: "00:00", dayOfWeek: 1, away: "02:30", roomId: 2 },
    { home1: "00:00", dayOfWeek: 2, away: "02:30", roomId: 2 },
    { home1: "00:00", dayOfWeek: 3, away: "02:30", roomId: 2 },
    { home1: "00:00", dayOfWeek: 6, away: "02:30", roomId: 2 },
    { home1: "00:00", dayOfWeek: 7, away: "02:30", roomId: 2 },
]

I attempted to loop over the rooms array as follows

const finalOutput = []
rooms.map((room) => {
    room.schedules.map((schedule) => {
        finalOutput.push(schedule)
    })
})

However, I am unsure how to identify and add the missing dayOfWeek values. Any assistance would be greatly appreciated. Thank you!

Answer №1

Unique solution for ES6:

const data = { rooms: [{ roomId: 1, schedules: [{ home1: "06:00", dayOfWeek: 1, away: "21:30", roomId: 1 }, { home1: "06:05", dayOfWeek: 2, away: "22:30", roomId: 1 } ] }, { roomId: 2, schedules: [{ home1: "06:00", dayOfWeek: 4, away: "21:30", roomId: 2 }, { home1: "06:05", dayOfWeek: 5, away: "22:30", roomId: 2 } ] } ] }

const getSchedules = (room) => {
  let weekDays = [...Array(8).keys()]
  weekDays.shift()
  let days = weekDays.filter(x => !room.schedules.some(y => y.dayOfWeek == x))
  return days.map(y => ({ home1: "00:00", dayOfWeek: y, away: "02:30", roomId: room.roomId }))
}

console.log(data.rooms.reduce((r,c) => (r.push(...getSchedules(c)), r), [])

Lodash version with unique touch:

const data = { rooms: [{ roomId: 1, schedules: [{ home1: "06:00", dayOfWeek: 1, away: "21:30", roomId: 1 }, { home1: "06:05", dayOfWeek: 2, away: "22:30", roomId: 1 } ] }, { roomId: 2, schedules: [{ home1: "06:00", dayOfWeek: 4, away: "21:30", roomId: 2 }, { home1: "06:05", dayOfWeek: 5, away: "22:30", roomId: 2 } ] } ] }

const getSchedules = (room) => {
  let days = _.difference(_.range(1,8), _.map(room.schedules, 'dayOfWeek'))
  return days.map(y => ({ home1: "00:00", dayOfWeek: y, away: "02:30", roomId: room.roomId }))
}
console.log(_.reduce(data.rooms, (r,c) => (r.push(...getSchedules(c)), r), [])
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

The strategy involves utilizing the difference between the range of 1...7 and the current days in each room.schedule. This is achieved through a unique approach in both ES6 and Lodash versions, enhancing the overall outcome.

Answer №2

If you want to create an array representing all the days of the week and filter it based on whether a specific day exists in your schedules array, follow these steps:

Firstly, go through the filtered array and construct your objects accordingly:

const info = {details: [{detailId: 1,schedules: [{ home1: "06:00", dayOfWeek: 1, away: "21:30" },{ home1: "06:05", dayOfWeek: 2, away: "22:30" }]},{detailId: 2,schedules: [{ home1: "06:00", dayOfWeek: 4, away: "21:30" },{ home1: "06:05", dayOfWeek: 5, away: "22:30" }]}]}

const daysOfWeek = [1, 2, 3, 4, 5, 6, 7]
const format =  { home1: "00:00", away: "02:30", }

const detailsInfo = info.details.reduce((arr, {detailId, schedules}) => {
  // Identify missing days that are not present in the schedules
  let absent = daysOfWeek.filter(day => !schedules.find(s => s.dayOfWeek == day ))
  return arr.concat( ... absent.map(d => Object.assign({}, format, {dayOfWeek: d,detail: detailId})))
        
}, [])
console.log(detailsInfo)

Answer №3

Check out this code snippet

const data = {
    rooms: [
        {
            roomId: 1,
            schedules: [
                { home1: "06:00", dayOfWeek: 1, away: "21:30" },
                { home1: "06:05", dayOfWeek: 2, away: "22:30" }
            ]
        },
        {
            roomId: 2,
            schedules: [
                { home1: "06:00", dayOfWeek: 4, away: "21:30" },
                { home1: "06:05", dayOfWeek: 5, away: "22:30" }
            ]
        }
    ]
}
let output = []
for (let room of data.rooms) {
  let days = []
  room.schedules.map(s => days.push(parseInt(s.dayOfWeek)))
  days = new Set(days)
  for(let i = 1; i <= 7; i++) {
    if(!days.has(i)) output.push({ 'home1': '00:00', 'dayOfWeek': i, 'away': '02:30', 'roomId': room.roomId })
  }
}
console.log(output)

Answer №4

If you want to manipulate arrays in JavaScript, consider using a combination of functions like Array.prototype.reduce(), Array.prototype.concat(), Array.prototype.filter(), Array.prototype.find() and Array.prototype.map().

Here's an example code snippet demonstrating these functions:

const data = {rooms: [{roomId: 1,schedules: [{ home1: "06:00", dayOfWeek: 1, away: "21:30" },{ home1: "06:05", dayOfWeek: 2, away: "22:30" }]},{roomId: 2,schedules: [{ home1: "06:00", dayOfWeek: 4, away: "21:30" },{ home1: "06:05", dayOfWeek: 5, away: "22:30" }]}]}
const finalOuput = data.rooms.reduce((a, c) => a.concat(
  [1, 2, 3, 4, 5, 6, 7]
    .filter(d => !c.schedules.find(s => s.dayOfWeek === d))
    .map(availableDay => ({
      roomId: c.roomId,
      home1: '00:00',
      dayOfWeek: availableDay,
      away: '02:30'
    }))
), []);

console.log(finalOuput);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Troubleshooting: Unable to delete data using $http in AngularJS

When using the $http service in Angular JS to call an API for deleting a message, I am receiving a successful response but the value is not actually being deleted. Interestingly, when I directly access the same API in my browser, the message gets deleted s ...

React - utilizing dynamic properties using string values

I am facing a challenge in my test suite where I need to generate components with dynamic props. The desired components should look like this: <Button primary /> <Button secondary /> However, I am currently stuck at this point: [ &apos ...

Exploring Style Attribute Manipulation using vanilla JavaScript on Firefox

I searched for a similar question, but I couldn't find anything quite like it. I'm currently developing a JavaScript Slider plugin for various projects within our company. This requires me to manipulate styles on certain elements in the DOM. I&a ...

Observe the input value that has been entered

Currently, my task involves: Inserting an email address into a form and having that email appear in the following <div class="your-mail"></div> tag Here is the existing HTML code: <div class="wrap"> <main> ...

Efficiently running multiple PHP pages with just one simple click

Below is the code fragment that I currently have: <html> <script type="text/javascript"> function Run() {var a=["ONE" ,"TWO" ,"THREE", "FOUR", "FIVE"]; window.location.href = "index.php?w1=" +a;} </script> <body> <input type="b ...

How to decrypt a file with aes-256-cbc in node.js when the IV is undefined

Here are the encryption details: crypto.createHash('sha256').update('mySup3rC00lP4ssWord').digest() Initialization Vector: crypto.randomBytes(16) I followed the methods in this tutorial: https://medium.com/@brandonstilson/lets-enc ...

Utilizing Angular Components Across Various Layers: A Guide

Consider the following component structure: app1 -- app1.component.html -- app1.component.ts parent1 parent2 app2 -- app2.component.html -- app2.component.ts Is it possible to efficiently reuse the app2 component within the ap ...

CSS - Discovering the reason behind the movement of text post generation (animation)

I have a question regarding CSS animation, specifically the typewriting effect. I was able to successfully achieve the typewriting effect using animation. However, I noticed that even though I did not set any animation for transforming, once the text is g ...

What is the best way to verify identical array elements in php?

Hey there, I have an array with repeating dates and I want to count the number of times each date appears in the array. However, my current approach is giving me an error message Undefined offset: 0. <?php $array = array('2013-11-28','2 ...

Exploring the depths of Rx.ReplaySubject: Techniques for delaying the `next()` event

Confused Mind: Either I'm mistaken, or the whiskey is starting to take effect. (I can't rule out the possibility that I'm just going crazy. Apologies for that.) Assumption: My assumption was that ReplaySubject would emit a single value eve ...

Troubles encountered with the onclick event handling

Hey there, I've created a GSP and JavaScript code for implementing a functionality that removes files on click. JavaScript snippet function remove(attachmentId) { $(document).ready(function(){ $('.glyphicon-remove').click ( ...

Changing a number from 0 to 1 in a field using AngularJS (HTML5)

It's strange behavior. I am using an input field with the type set to number. When I enter 1230, the model value remains as 1230. However, when I type 01, it becomes 1. Even though I can see 01 in the input value, there seems to be something relate ...

Sequelize: Establishing multiple connections

Currently working with Sequelize in Node, I have two tables named User and Auth: User id name Auth: id token My goal is to establish relationships between these models. A User can possess multiple Auth entries, forming a to-many relati ...

I am puzzled as to why the number displayed by my array_sum function is incorrect

I have encountered a puzzling issue with an array manipulation task: $sustainCapital_arr = Array ( [0] => 2,759 [1] => 3,269 [2] => 3,481 [3] => 3,573 [4] => 3,997 [5] => 4,421 [6] => 10,999 ) When trying to calculate the sum of the v ...

Leveraging the identical data synchronously within the same useEffect block

My task involves fetching data in two different ways and rendering it accordingly. Initially, I need to retrieve each item one by one and increment the count. Once that is done, I should fetch all the data at once and update the display. To achieve this, I ...

Combining Socket.io with AJAX for real-time web applications

I am currently working on a web application that relies on Socket.io for delivering notifications to users. I'm wondering if it would be more beneficial to utilize Socket.io exclusively for all client-server communication, or if mixing in traditional ...

What's the most effective method for updating the title of the date header on MUI Date Picker?

Does anyone know how to customize the title of the Calendar in MUI Date Picker? I want to add a specific string to the display that shows the month and year, like "August 2014." https://i.stack.imgur.com/qgMun.png I've searched the API but couldn&ap ...

Unable to show information within input field

I am attempting to present the value of my variable in a textBox using Jade, but I am encountering issues. I have tried the following options: value="#{startDate}" value="#{{startDate}}" value="{startDate}" value={{startDate}} I am aware that it is func ...

What is the method for adding a new value to an array stored in a data attribute using square brackets around a text input?

I am dealing with an element that contains an array specified in the following code snippet: <div class="home_team" data-home='["10","20","30"]'></div> Whenever I input a value in the text fi ...

Tips for implementing an HTML modal with AngularJS binding for a pop up effect

As a beginner in AngularJS, I am facing a challenge. I have an HTML page that I want to display as a pop-up in another HTML page (both pages have content loaded from controllers). Using the router works fine for moving between pages, but now I want the s ...