Contrast the differences between arrays and inserting data into specific index positions

In this scenario, I have two arrays structured as follows:

arr1=[{room_no:1,bed_no:'1A'},
      {room_no:1,bed_no:'1B'},
      {room_no:2,bed_no:'2A'},
      {room_no:3,bed_no:'3A'},
      {room_no:3,bed_no:'3B'},
      {room_no:4,bed_no:'4A'}]

 arr2=[
       { patient_details:[{name:'patient1',age:22}],
         patient_room_details:[{room_no:1,bed_no:'1A'}],
         status:'occupied'
       },
       { patient_room_details:[{room_no:1,bed_no:'1B'},
         status:'available'
       },
       {  patient_details:[{name:'patient2',age:32}],
          patient_room_details:[{room_no:2,bed_no:'2A'}],
          status:'occupied'
       }
       { patient_room_details:[{room_no:3,bed_no:'3A'},
         status:'cleaning'
       },
      ]  

The goal is to compare the room_no and bed_no from the first array with the second array's patient_room_details. If a match is found, the object with patient_details, patient_room_details, and status is added to a result array. If no match is found, the status 'AVAILABLE' should be pushed.

Unfortunately, I'm facing issues pushing the status as AVAILABLE when there are no matches. Any assistance on this matter would be greatly appreciated.

The desired final outcome would look like this:

result=[
       { patient_details:[{name:'patient1',age:22}],
         patient_room_details:[{room_no:1,bed_no:'1A'}],
         status:'occupied'
       },
       { patient_room_details:[{room_no:1,bed_no:'1B'},
         status:'available'
       },
       {  patient_details:[{name:'patient2',age:32}],
          patient_room_details:[{room_no:2,bed_no:'2A'}],
          status:'occupied'
       },
       { patient_room_details:[{room_no:3,bed_no:'3A'},
         status:'cleaning'
       },
       { patient_room_details:[{room_no:3,bed_no:'3B'},
         status:'available'
       },
       { patient_room_details:[{room_no:4,bed_no:'4A'},
         status:'available'
       },
      ]

Answer №1

Array.prototype.map() and Map are powerful tools that can work together to efficiently compare arrays using keys.

Below is a practical example demonstrating this.

// Input.
const rooms = [{room_no: 1, bed_no: '1A'}, {room_no: 1, bed_no: '1B'}, {room_no: 2, bed_no: '2A'}, {room_no: 3, bed_no: '3A'}, {room_no: 3, bed_no: '3B'}, {room_no: 4,bed_no: '4A'}]
const patients = [{patient: {name: 'patient1', age: 22}, room: {room_no: 1,bed_no: '1A'}, status: 'occupied'}, {room: {room_no: 1, bed_no: '1B'}, status: 'available'}, {patient: {name:'patient2',age:32}, room: {room_no:2,bed_no: '2A'}, status:'occupied' }, {room: {room_no: 3, bed_no:'3A'}, status: 'cleaning'}]

// Room Status function.
const roomStatus = (rooms, patients) => (m => rooms.map(r => m.get(`${r.room_no} ${r.bed_no}`) || {room: r, status: 'available'}))(new Map(patients.map(x => [`${x.room.room_no} ${x.room.bed_no}`, x]))

// Output.
const output = roomStatus(rooms, patients)

// Logging the result for proof.
console.log(output)

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 am just starting to explore firebase and I'm having trouble organizing my data. I've attempted to use the query function and orderBy

After experimenting with query and orderBy() methods, I'm still struggling to properly integrate it into my code. Here's what I have so far: Methods: async saveMessage(){ try { const docRef = await addDoc(collection(db, "chat"), ...

Unique option preservation on customized HTML select menus - Maintain original selection

Currently, I am attempting to replicate a custom HTML select based on the example provided by W3 Schools. You can view the demo through this link: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_custom_select The issue I am encountering is that ...

Retrieving pals from the API and showcasing them on the user interface

Currently, I am working on a project involving a unique Chat Application. While progressing with the development, I encountered an issue related to fetching friends data from the backend (node). Even though I can successfully retrieve the friends data in ...

The style of MUI Cards is not displaying properly

I've imported the Card component from MUI, but it seems to lack any styling. import * as React from "react"; import Box from "@mui/material/Box"; import Card from "@mui/material/Card"; import CardActions from "@mui/m ...

In TypeScript, combining the numbers 0 and 1 results in the value 01

I am in the process of developing a Shopping Card feature. private _card: Map<Product, number> = new Map<Product, number>(); ... addToCard(prod: Product, amount: number = 1): void { const totalAmount: number = this._card.get(prod) + amou ...

Show errors related to parsley within a bootstrap tooltip

I am currently working with Parsley 2.0.0-rc5 and I would like to display the error messages using a Bootstrap tooltip. The issue I am facing is that the "parsley:field:error" event fires before the error message is displayed in the error container, maki ...

I prefer to have static modules generated on the home page rather than dynamic ones

As a newcomer to Angular, I am facing an issue with dynamic modules in my project. Currently, all modules are being generated when I run the project, but I only want to generate the login page module. Below is a screenshot and the code from the app.routing ...

What are the steps for transmitting an array of data to Parse Cloud Code?

Trying to send an array of contact emails as a parameter in Cloud Code function for Parse, here is how I am doing it: HashMap<String, ArrayList<String>> params = new HashMap<>(); ArrayList<String> array = new ArrayList<>(); a ...

Running a JavaScript script after loading a page via AJAX is not functioning as expected

As I am attempting to retrieve a page using AJAX, I've encountered an issue where any Javascript code included on that page fails to execute. Why is this happening? The simple JavaScript code present in my ajax page is as follows: <script type=" ...

Including content without triggering the digest cycle (utilizing raw HTML) within a Directive

My goal is to include raw HTML inside a directive for later transclusion (to populate a modal when opened). The issue arises when the contents of dialog-body are executed, triggering the ng-repeat loop and causing the template to be rerun, leading to a po ...

Learning to retrieve specific properties from an event target in JavaScript

Here is the code snippet I am working with: <h1 msgId = "someId"> Some text </h1> And in my code.js file, I have the following function: document.addEventListener('click', function(e) { target = e.target; }, false); I am tryin ...

Guide to sending data from an HTML page to a MVC Controller using WebApi

How can I fix the issue with my HTML button not calling the API properly? function saveclickdata() { var allData = { InvNo:document.getElementById('TbInvNo').value, GrossSale:document.getElementById('Tb ...

(React Native) Creating a visually appealing grid layout for displaying an array of item cards

I am working with two arrays named 'word' and 'definition' export default class Dictionary extends React.Component { constructor(props) { super(props); this.state = { word: [], definition:[], index: ...

Mongoose/JS - Bypassing all then blocks and breaking out of the code

If I need to check if a certain ID exists and exit the process if an error is encountered right from the beginning, is there a more concise way to do it rather than using an if-else block? For example: Question.find({_id: req.headers['questionid&ap ...

Is there a way to verify HTML binding prior to setting up an AngularJS directive?

On a page where I utilized a custom select-box directive to display the Month, certain arguments are required by the directive: <custom-select-box id="month" model="month" model-required model-name="month" options="month.value ...

Transfer the "file" from the busboy to the GM for FTP uploading

I'm looking to resize an uploaded image using nodejs and send it via ftp. I'll be utilizing nodejs, busboy, GraphicsMagick, and jsftp. var uploadFile = function(dir, req, cb) { req.busboy.on('file', function(fieldname, file, filename, ...

What is the best way to invoke an external JavaScript source using another JavaScript source?

I am trying to connect 2 different files together. file1.php and document.html file1.php has the following code in it: document.writeln('< script src="https://www.googletagservices.com/tag/js/gpt.js"> googletag.pubads().definePassback ...

How can I extract echoed information from PHP after submitting form data through jQuery Ajax?

I am looking to transfer a file from an input form to a php script using ajax and handle the response echoed by my php script. Here is my HTML form: <form id="fileUploadForm" method="POST" enctype="multipart/form-data"> <input name="fileToU ...

What other choices are available for the Angular ui-select2 directive?

Within the Angular select2 controller below: <select ui-select2 id="projectListSelection" data-placeholder="Select a Project ..." ng-model="selectedProject"> @*ng-options="project.WebsiteName for project in projectList"*@ ...

Change the ddmmyy date string to dd/mm/yyyy format using TypeScript

When I use the date picker onchange method, the date is passed as a string like ddmmyyyy (20102020) to dd/mm/yyyy. I am unsure of how to convert the date format from ddmmyyyy to dd/mm/yyyy. In the CustomDateParserFormatter, the string needs to be converted ...