Combine arrays if the objects inside them are identical

Is anyone online? I need help. I have an array structured like this.

var array = [ {
roomNumber: 'R01',
roomType: 'Deluxe',
basic_facilities: 'Hot Water',
additional_facilities: 'Iron' },
    {
roomNumber: 'R01',
roomType: 'Deluxe',
basic_facilities: 'Minibar',
additional_facilities: 'AC' },
    {
roomNumber: 'R01',
roomType: 'Deluxe',
basic_facilities: 'cold Water',
additional_facilities: 'Fan' },
    {
roomNumber: 'R02',
roomType: 'standerd',
basic_facilities: 'View',
additional_facilities: 'Washing' },
         {
roomNumber: 'R02',
roomType: 'standerd',
basic_facilities: 'View 2',
additional_facilities: 'wash' }
    ]

I want to transform it into the following format.

var result =[{
roomNumber: 'R01',
roomType: 'Deluxe',
basic_facilities: ['Hot Water','Minibar','cold Water'],
additional_facilities: ['Iron','AC','fan'] },{
roomNumber: 'R02',
roomType: 'standerd',
basic_facilities: ['View','View 2'],
additional_facilities: ['Washing','wash'] }]

I understand this is a fundamental task, but I require assistance with it. Thank you.

This is what I have accomplished thus far.

 var array = [ {
roomNumber: 'R01',
roomType: 'Deluxe',
basic_facilities: 'Hot Water',
additional_facilities: 'Iron' },
    {
roomNumber: 'R01',
roomType: 'Deluxe',
basic_facilities: 'Minibar',
additional_facilities: 'AC' },
    {
roomNumber: 'R01',
roomType: 'Deluxe',
basic_facilities: 'cold Water',
additional_facilities: 'Fan' },
    {
roomNumber: 'R02',
roomType: 'standerd',
basic_facilities: 'View',
additional_facilities: 'Washing' },
         {
roomNumber: 'R02',
roomType: 'standerd',
basic_facilities: 'View 2',
additional_facilities: 'wash' }
    ]
    result = [];

array.forEach(function (a) {
    if (!this[a.roomNumber]) {
        this[a.roomNumber] = { roomNumber: a.roomNumber};
        result.push(this[a.roomNumber]);
    }
}, Object.create(null));

 console.log(result);

Answer №1

It seems like the approach you're taking involves consolidating items into an object while iterating, which is a step in the right direction. However, the recommended method to achieve this is by using the reduce function. In this function, the value returned from the previous iteration (or the initial value on the first iteration) is passed as the first argument to the callback function.

During each iteration, you should check if the roomNumber exists on the accumulator object. If it doesn't, create a new object with the basic and additional facilities arrays for that roomNumber. Finally, use Object.values to convert the object into an array of its values:

var array = [
  {
    roomNumber: 'R01',
    roomType: 'Deluxe',
    basic_facilities: 'Hot Water',
    additional_facilities: 'Iron'
  },
  {
    roomNumber: 'R01',
    roomType: 'Deluxe',
    basic_facilities: 'Minibar',
    additional_facilities: 'AC'
  },
  {
    roomNumber: 'R01',
    roomType: 'Deluxe',
    basic_facilities: 'Cold Water',
    additional_facilities: 'Fan'
  },
  {
    roomNumber: 'R02',
    roomType: 'Standard',
    basic_facilities: 'View',
    additional_facilities: 'Washing'
  },
  {
    roomNumber: 'R02',
    roomType: 'Standard',
    basic_facilities: 'View 2',
    additional_facilities: 'Wash'
  }
];

const roomsByRoomNumber = array.reduce((accumulator, item) => {
  const { roomNumber, roomType, basic_facilities, additional_facilities } = item;
  if (!accumulator[roomNumber]) {
    accumulator[roomNumber] = { roomNumber, roomType, basic_facilities: [], additional_facilities: [] };
  }
  accumulator[roomNumber].basic_facilities.push(basic_facilities);
  accumulator[roomNumber].additional_facilities.push(additional_facilities);
  return accumulator;
}, {});
const result = Object.values(roomsByRoomNumber);
console.log(result);

Answer №2

Do you need to combine arrays based on the elements roomNumber and roomType? One way to accomplish this is by using the reduce() and findIndex() methods.

var arr = [ {roomNumber: 'R01',roomType: 'Deluxe',basic_facilities: 'Hot Water',additional_facilities:'Iron' },
   {roomNumber: 'R01',roomType: 'Deluxe',basic_facilities: 'Minibar',additional_facilities: 'AC' },
    {roomNumber: 'R01',roomType: 'Deluxe',basic_facilities: 'cold Water',additional_facilities: 'Fan' },
    {roomNumber: 'R02',roomType: 'standerd',basic_facilities: 'View',additional_facilities: 'Washing' },
    {roomNumber: 'R02',roomType: 'standerd',basic_facilities: 'View 2',additional_facilities: 'wash' }
]

let mkeys = ['roomNumber','roomType']
let ckeys = ['basic_facilities','additional_facilities']
let result = arr.reduce((ac,a) => {
  let ind = ac.findIndex(x => mkeys.every(key => x[key] === a[key]));
  a = JSON.parse(JSON.stringify(a));
  ckeys.forEach(key => a[key] = [a[key]]);
  ind === -1 ? ac.push(a) : ckeys.forEach(key => ac[ind][key].push(a[key][0]));
  return ac;
},[])
console.log(result);

Answer №3

Yet another way to solve this...

...
const resultList = [];
for (const currentRoom of roomArray) {
  const foundRoom = resultList.find(r => r.roomNumber == currentRoom.roomNumber);
  if (foundRoom) {
     foundRoom.basic_facilities.concat(currentRoom.basic_facilities);
     foundRoom.additional_facilities.concat(currentRoom.additional_facilities);
  } else {
     resultList.push(currentRoom);
  }
} 

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

When I try to import script files into my ASP.NET page, Intellisense displays the methods accurately. However, when I attempt to call one of them, an

I added a function to an existing .js file (I tried two different files) in order to make the method accessible in multiple locations without having to repeat the code. I also created a simple function just to confirm that my function wasn't causing a ...

Error: The JQUERY autocomplete is throwing an uncaught type error because it cannot read the property 'length' of an undefined value

These scripts are being utilized at this source I have implemented jQuery Autocomplete to search for users in my database. Below is the controller code returning Json: public function searchusers1() { if ($_GET) { $query = $this -> input ...

Steps to avoid IE11 prompt (Do you really want to leave this site)

In the midst of making a webpage, I find myself faced with the peculiar issue of only having a dropdown to select. To make matters worse, when attempting to navigate to the next page in IE11, a pesky message pops up. Curious about the default behavior of ...

React JS Button remains unaltered despite API call influence

I have encountered an issue with my page where a single post is displayed and there is a like button. The problem arises when the user clicks the like button - if the post is already liked, the button state should change to an unlike button. However, if th ...

Using a series of nested axios requests to retrieve and return data

Currently, I am utilizing Vue and executing multiple calls using axios. However, I find the structure of my code to be messy and am seeking alternative approaches. While my current implementation functions as intended, I believe there might be a more effic ...

Retrieving object by a value within a nested array in Javascript

I need to retrieve all objects that have a specific 'id' within a nested array. Specifically, I want to find all person objects with hobbies id of 2 (hiking) in the provided sample data. This inquiry tackles the challenge of extracting all value ...

What is causing the inability to successfully copy and paste Vega editor specs locally?

I successfully executed this spec in Vega Editor: { "$schema": "https://vega.github.io/schema/vega/v3.0.json", "width": 1, "height": 1, "padding": "auto", "data": [ { "name": "source", "values": [ {"name": "Moyenne","vo ...

Strange occurrences within the realm of javascript animations

The slider works smoothly up until slide 20 and then it suddenly starts cycling through all the slides again before landing on the correct one. Any insights into why this is happening would be greatly appreciated. This issue is occurring with the wp-coda- ...

Converting the 'require' call to an import may be a more efficient method when importing package.json in a typescript file

In my current project, I am creating a class where I am directly accessing the package version number like this: const pkg = require('../package.json') export class MyClass() { constructor() { // Set the base version from package.jso ...

Angular - Showcasing Nested Objects in JSON

I am experimenting with using angular ngFor to iterate through this data: Link: Although I can successfully retrieve the data by subscribing to it, I encounter an issue when trying to display attributes that contain objects. The output shows as [object O ...

Updating state within an eventListener in useEffect with an empty array does not trigger a re-render

This text is unique because I tried to enhance it with an updater function that did not yield the desired result. Here is the code snippet: const [counter, setCounter] = useState(0); useEffect(()=> { const fetchSessions =async ()=> ...

Invalid function call detected, transitioning from Reactjs to Nextjs

After spending some time away from the ReactJS world, I decided to make a comeback and try my hand at NextJS. Unfortunately, I ran into an issue with an Invalid Hook Call. I'm in the process of transitioning my ReactJS project to NextJS. To illustrat ...

What could be causing my program to malfunction once the array has more than 3 inputs?

I decided to create an array to store a variety of numbers for manipulation. My goal was to iterate through the array, selecting two numbers at a time and checking if their sum equals the global variable "target". Strangely, when I input more than 3 number ...

Creating a JSON object from two arrays is a simple process

Consider the following two arrays: let values = ["52", "71", "3", "45", "20", "12", "634", "21"]; let names = ["apple", "orange", "strawberry", &q ...

How to apply CSS styling to a specific element using jQuery

When using $(".className"), all elements with the class .className are returned. How can I target a specific element by its index number to apply styling only to that element? <html> <head> <script src="https://ajax.googleapis.com/ajax ...

Tips for executing an SQL query containing a period in its name using JavaScript and Node.JS for an Alexa application

Hello there, I've been attempting to make Alexa announce the outcomes of an SQOL query, but I'm encountering a persistent error whenever I try to incorporate owner.name in the output. this.t("CASEINFO",resp.records[0]._fields.casenumber, resp.r ...

What could be causing my table to not display?

I imported a CSV file with data on time, events, and location. The data was loaded into separate arrays for each column. I attempted to display the arrays as an HTML table using a for loop, but the table is not showing up. What could be causing this issue? ...

Property of object (TS) cannot be accessed

My question relates to a piece of TypeScript code Here is the code snippet: export function load_form_actions() { $('#step_2_form').on('ajax:before', function(data) { $('#step_2_submit_btn').hide(); $(&ap ...

Leveraging Node.js to establish a connection between two pug files

Recently, I decided to delve into the world of pug and JavaScript. However, I seem to be facing a small issue that I can't quite figure out on my own. My project involves creating multiple .pug files with various text content that I can navigate betwe ...

An unrecoverable error has occurred in the SetForm function: PHPMailer::SetForm() method is not defined

While working on form validation in jQuery with a WAMP server, I encountered two errors: Fatal error: Uncaught Error: Call to undefined method PHPMailer:: SetForm() and Error: Call to undefined method PHPMailer::SetForm(). I have already added PHPMailerAu ...