Merge multiple arrays into a single array

In this scenario, given the array provided, I am trying to achieve the desired output by modifying the reduce function. While attempting to assign [cur] to a plans key, I noticed that it is only extracting the first element. I suspect the issue lies in the way I am concatenating the objects, but I am unable to solve it on my own.

{
   employee: 'employee_1',
   customer: {
     name: 'customer_1',
   },
   startdate: '2020-03-01T23:00:00.000Z'
}, {
   employee: 'employee_2',
   customer: {
     name: 'customer_1',
   },
   startdate: '2020-03-01T23:00:00.000Z'
}, {
   employee: 'employee_3',
   customer: {
     name: 'customer_1',
   },
   startdate: '2020-03-01T23:00:00.000Z'
}
plans.reduce(function(o, cur) {

   // Get the index of the key-value pair.
   var occurs = o.reduce(function(n, item, i) {
      return (item.customer.toString() === cur.customer.toString()) ? i : n;
   }, -1);

   // If the name is found,
   if (occurs >= 0) {
      // append the current value to its list of values.
      o[occurs].employee = o[occurs].employee.concat(cur.employee)
      o[occurs].startdate = o[occurs].startdate.concat(cur.startdate)

   // Otherwise
   } else {

      // add the current item to o (but make sure the value is an array).
      var obj = {
         customer: cur.customer,
         employee: [cur.employee],
         startdate: [cur.startdate]
      };
      o = o.concat([obj]);
   }
   return o;
}, [])

This function reduces the given array to something like this:

{
   customer: {
     name: 'customer_1'
   },
   employee: [{
     employee: 'employee_1'
   }, {
     employee: 'employee_2'
   }, {
     employee: 'employee_3'
   }],
   startdate: [{
     startdate: '2020-03-01T23:00:00.000Z'
   }, {
     startdate: '2020-03-01T23:00:00.000Z'
   }, {
     startdate: '2020-03-01T23:00:00.000Z'
   }]  
}

However, the desired output should look like this:

{
   customer: {customer_data},
   plans: [{
     employee: 'employee_1',
     startdate: '2020-03-01T23:00:00.000Z' 
   }, {
     employee: 'employee_2',
     startdate: '2020-03-01T23:00:00.000Z' 
   }, {
     employee: 'employee_3',
     startdate: '2020-03-01T23:00:00.000Z' 
   }]
}

Answer №1

I have made some adjustments to your solution in order to achieve the desired output.

Instead of utilizing the reduce method, I suggest using the find method to verify if the customer already exists in the array. Additionally, it seems you overlooked the plans array, so I have integrated that into the code.

var plans = [
{
   employee: 'employee_1',
   customer: {
     name: 'customer_1',
   },
   startdate: '2020-03-01T23:00:00.000Z'
}, {
   employee: 'employee_2',
   customer: {
     name: 'customer_1',
   },
   startdate: '2020-03-01T23:00:00.000Z'
}, {
   employee: 'employee_3',
   customer: {
     name: 'customer_1',
   },
   startdate: '2020-03-01T23:00:00.000Z'
}
];


var result = plans.reduce(function(o, cur) {

   // Locate the index of the key-value pair.
   var occurs = o.find(ob=> ob.customer.name === cur.customer.name);

   // If the customer name is located,
   if (occurs) {
      // append the current value to its existing list of values.
      occurs.plans.push( {employee: cur.employee,
          startdate: cur.startdate}  )
   // If not found
   } else {

      // include the current item to o (ensuring the value is an array).
      var obj = {
         customer: cur.customer,
         plans:[
          {employee: cur.employee,
          startdate: cur.startdate}
         ]
      };
      o = o.concat(obj);
   }
   return o;
}, [])

console.log(result)

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

Exploring the wonders of ExpressJS session variables

Having transitioned from a PHP background to focusing on JS, I find myself adjusting to the differences in handling session variables. In PHP, the $_SESSION global variable was very convenient as it allowed easy access to session data throughout the code. ...

Is there a way to automatically implode array chunks in PHP?

i have a chunked array: Array( [0] => Array ( [0] => "0" [1] => "1" [2] => "2" ) [1] => Array ( [3] => "3" [4] => "4" [5] => "5" ) [2] => Array ( [5] =& ...

What is the best way to gradually transform a continuously shifting text color into a single, consistent hue?

Hey there, wonderful people of StackOverflow! I am absolutely stumped and cannot figure out how to smoothly transition this color-changing text from its current state into a different solid color when the submit button is clicked. Is there a skilled indiv ...

Angular component equipped with knowledge of event emitter output

I have a custom button component: @Component({ selector: "custom-submit-button" template: ` <button (click)="submitClick.emit()" [disabled]="isDisabled"> <ng-content></ng-content> </butto ...

Need help fixing my issue with the try-catch functionality in my calculator program

Can someone assist me with my Vue.js calculator issue? I am facing a problem where the output gets added to the expression after using try and catch. How can I ensure that both ERR and the output are displayed in the {{output}} section? Any help would be a ...

Filtering tables in Angular 6 using checkbox options

I have a functional code snippet that filters a table using checkboxes. However, I am facing an issue when unchecking a checkbox. It does not return the original array as expected. .html <ng-container *ngFor="let group of groups"> <label cla ...

Error in fullCalendar where events are appearing on incorrect days in the month view of the current month

https://i.sstatic.net/v8Faj.png My fullcalendar plug-in is causing some trouble. I'm trying to show events in the monthview of the calendar, but when I'm in the current month, events on the same day of the week are not displaying correctly. They ...

The Puppeteer software does not automatically shut down the browser once the task is complete

Currently, I have set up puppeteer on my Ubuntu server with Express and Node.js like so: var puppeteer = require('puppeteer'); var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/&ap ...

Choosing a specific page number - kendo grid

Currently, I am working on creating a grid using kendo-telrik. Let's say I have 100 data items, but in the JSON format, I only have 10 data items (assuming each page contains 10 data items for pagination). However, I want to display all the pages (10 ...

When the button is clicked, I would like to use JavaScript to toggle the visibility of a div, allowing it to open and

I am attempting to toggle a div using JavaScript when the open and close button is clicked. However, I have encountered an issue where the div disappears when the button is clicked, possibly due to post-back. var toggle = function () { var mydiv = d ...

An elaborate warning mechanism in Redux-observable that does not trigger an action at the conclusion of an epic

I'm currently working on implementing a sophisticated alert system using redux and redux-observable. The requirements are: An action should request an alert: REQUEST_ALERT An action should create an alert and add an ID: SET_ALERT (handled in the ep ...

Generate a fresh object if the values within the TypeScript object are identical

How can I filter an object to return a new object containing elements with the same values? For example: allValues = {"id1": 3, "id2": 4, "id3": 3} The desired output is: filteredValues = {"id1": 3, "id3": 3} This is because the keys "id1" and "id3" hav ...

"I'm trying to incorporate react-datepicker into my ReScript application, but I'm struggling to

I am attempting to incorporate an external library like react-datepicker into my project. Below is the code snippet and how I am using it: module DatePicker = { @react.component @module("react-datepicker") external make: () => React.eleme ...

What is the most effective way to transform values into different values using TypeScript?

If I have a list of country codes and I want to display the corresponding country names in my component, how can I achieve this using props? interface MyComponentProps { countryCode: 'en' | 'de' | 'fr'; } const MyComponent: ...

Ways to customize the bootstrap-datetimepicker to display time in 15-minute increments

Here is my code in JavaScript to increment by minutes at a 1-hour interval: fillMinutes = function () { var table = widget.find('.timepicker-minutes table'), currentMinute = viewDate.clone().startOf('h'), ...

Guide on how to showcase the template by leveraging the roomList information with ngTemplateOutlet in Angular

TS roomList = [{ name: 'Room2' }] HTML <div class="Layout-body"> <ng-container *ngFor="let dt of roomList; index as i" [ngTemplateOutlet]="Room1" [ngTemplateOutletContext]="{ data: dt, i: i }&qu ...

Visualizing JSON data in React.js using Chart.js

Currently, as a beginner in ReactJS, I am working on an application that displays COVID-19 data from a JSON API in a visual format using Chart.js. However, despite trying various solutions, I am unable to visualize the data. Below is my source code: App ...

javascript guide to dynamically update the glyphicon based on value changes

I am attempting to implement an optimal level feature where a glyphicon arrow-up will be displayed if a value falls within the optimum range, and it will switch to a glyphicon arrow-down if the value is lower. <div class="card-body" ng-repeat="item i ...

Problem encountered while downloading dependencies with Snyk

While attempting to set up the dependencies for the W3C Respec project, I encountered this error message: npm WARN prepublish-on-install As of npm@5, `prepublish` scripts are deprecated. npm WARN prepublish-on-install Use `prepare` for build steps and `pr ...

Having trouble notifying a json object following an ajax request

My project involves using a PHP file that contains an array with multiple values. Additionally, I have an HTML page that features a single input field. A listener is set up to detect changes in the input field. Once a change occurs, an AJAX call is trigge ...