Merging arrays of objects in JavaScript to create a fresh one

I am struggling to combine two sets of data into a single array by matching them based on the day. I want to create a new array of objects that include the relevant information from both sets. The first set includes the following:

[
  { date: '9/30/2017', day: 'Saturday' },
  { date: '10/1/2017', day: 'Sunday' },
  { date: '10/2/2017', day: 'Monday' },
  { date: '10/3/2017', day: 'Tuesday' },
  { date: '10/4/2017', day: 'Wednesday' },
  { date: '10/5/2017', day: 'Thursday' },
  { date: '10/6/2017', day: 'Friday' },
  { date: '10/7/2017', day: 'Saturday' },
  { date: '10/8/2017', day: 'Sunday' },
  { date: '10/9/2017', day: 'Monday' },
  { date: '10/10/2017', day: 'Tuesday' }
]

and

[
 {
    day: 'Sunday',
    totalHours: 10,
    serveTimes: [ { startTime: 5, stopTime: 15 } ]
  },
  {
    day: 'Monday',
    totalHours: 10,
    serveTimes: [ { startTime: 5, stopTime: 10 }, { startTime: 15, stopTime: 20 } ]
  },
  {
    day: 'Tuesday',
    totalHours: 3,
    serveTimes: [ { startTime: 2, stopTime: 5 } ]
  },
  {
    day: 'Wednesday',
    totalHours: 10,
    serveTimes: [ { startTime: 5, stopTime: 15 } ]
  },
  {
    day: 'Thursday',
    totalHours: 5,
    serveTimes: [ { startTime: 5, stopTime: 7 }, { startTime: 20, stopTime: 23 } ]
  },
  {
    day: 'Friday',
    totalHours: 5,
    serveTimes: [ { startTime: 5, stopTime: 10 } ]
  },
  {
    day: 'Saturday',
    totalHours: 10,
    serveTimes: [ { startTime: 5, stopTime: 10 }, { startTime: 13, stopTime: 18 } ]
  }
]

This was the code I used:

function finalFormat (a, d) {
  var combined = a.concat(d)
  var final = _(combined)
    .groupBy('day')
    .map(_.spread(_.assign))
    .value()
  return final
}

However, the resulting array is missing data for some dates as shown below:

[...]

It lacks information for all dates, and I'm feeling stuck. Can someone offer guidance?

Answer №1

You can utilize the map method for this task. Another option is to employ the Map collection, which allows for constant time complexity (O(1)) when accessing items during the mapping process:

const uniqueDays = new Map(secondArray.map(s => [s.day, s]));
const result = firstArray.map(({date, day})=> ({date, ...uniqueDays.get(day)}));

Here's an example:

const firstArray = [
  { date: '9/30/2017', day: 'saturday' },
  { date: '10/1/2017', day: 'sunday' },
  { date: '10/2/2017', day: 'monday' },
  { date: '10/3/2017', day: 'tuesday' },
  { date: '10/4/2017', day: 'wednesday' },
  { date: '10/5/2017', day: 'thursday' },
  { date: '10/6/2017', day: 'friday' },
  { date: '10/7/2017', day: 'saturday' },
  { date: '10/8/2017', day: 'sunday' },
  { date: '10/9/2017', day: 'monday' },
  { date: '10/10/2017', day: 'tuesday' }
];

const secondArray = [
  {
     day: 'sunday',
     totalHours: 10,
     serveTimes: [ { startTime: 5, stopTime: 15 } ]
   },
   {
     day: 'monday',
     totalHours: 10,
     serveTimes: [ { startTime: 5, stopTime: 10 }, { startTime: 15, stopTime: 20 } ]
   },
   {
     day: 'tuesday',
     totalHours: 3,
     serveTimes: [ { startTime: 2, stopTime: 5 } ]
   },
   {
     day: 'wednesday',
     totalHours: 10,
     serveTimes: [ { startTime: 5, stopTime: 15 } ]
   },
   {
     day: 'thursday',
     totalHours: 5,
     serveTimes: [ { startTime: 5, stopTime: 7 }, { startTime: 20, stopTime: 23 } ]
   },
   {
     day: 'friday',
     totalHours: 5,
     serveTimes: [ { startTime: 5, stopTime: 10 } ]
   },
   {
     day: 'saturday',
     totalHours: 10,
     serveTimes: [ { startTime: 5, stopTime: 10 }, { startTime: 13, stopTime: 18 } ]
   }
 ];

 const uniqueDays = new Map(secondArray.map(s => [s.day, s]));
 const result = firstArray.map(({date, day})=> ({date,  ...uniqueDays.get(day)}));
 console.log(result);

Answer №2

var weekdays = [
  { date: '9/30/2017', day: 'saturday' },
  { date: '10/1/2017', day: 'sunday' },
  { date: '10/2/2017', day: 'monday' },
  { date: '10/3/2017', day: 'tuesday' },
  { date: '10/4/2017', day: 'wednesday' },
  { date: '10/5/2017', day: 'thursday' },
  { date: '10/6/2017', day: 'friday' },
  { date: '10/7/2017', day: 'saturday' },
  { date: '10/8/2017', day: 'sunday' },
  { date: '10/9/2017', day: 'monday' },
  { date: '10/10/2017', day: 'tuesday' }
];

var activities = [
 {
    day: 'sunday',
    totalHours: 10,
    serveTimes: [ { startTime: 5, stopTime: 15 } ]
  },
  {
    day: 'monday',
    totalHours: 10,
    serveTimes: [ { startTime: 5, stopTime: 10 }, { startTime: 15, stopTime: 20 } ]
  },
  {
    day: 'tuesday',
    totalHours: 3,
    serveTimes: [ { startTime: 2, stopTime: 5 } ]
  },
  {
    day: 'wednesday',
    totalHours: 10,
    serveTimes: [ { startTime: 5, stopTime: 15 } ]
  },
  {
    day: 'thursday',
    totalHours: 5,
    serveTimes: [ { startTime: 5, stopTime: 7 }, { startTime: 20, stopTime: 23 } ]
  },
  {
    day: 'friday',
    totalHours: 5,
    serveTimes: [ { startTime: 5, stopTime: 10 } ]
  },
  {
    day: 'saturday',
    totalHours: 10,
    serveTimes: [ { startTime: 5, stopTime: 10 }, { startTime: 13, stopTime: 18 } ]
  }
];

var updatedWeekdays = [];

weekdays.forEach(function(day){
    activities.forEach(function(activity){
        if(day.day === activity.day){
            day.totalHours = activity.totalHours;
            day.serveTimes = activity.serveTimes;
        }
    });
    updatedWeekdays.push(day);
});

You can simplify this further using different array methods like map, filter, or reduce. This is just one way to approach it.

Answer №3

Your arrays have different sizes - the first array contains 11 objects, while the second array has only 7 objects.

  • Determine which array is larger by comparing their sizes using the .length property.

  • Select a common key that all objects share (e.g. "day").

  • Iterate through the larger array (the first array - referred to as dates in the example).

  • Within each iteration of the larger array, go through the smaller array (the second array - called hours in the demo) to find the key of the current object and match its value with the objects in the smaller array. For instance, an object in dates with

    "day": "friday"
    should align with the object in hours that also has
    "day": "friday"
    .

  • Whenever there is a match, merge the objects using Object.assign().

Demo

let dates=[{date:"9/30/2017",day:"saturday"},{date:"10/1/2017",day:"sunday"},{date:"10/2/2017",day:"monday"},{date:"10/3/2017",day:"tuesday"},{date:"10/4/2017",day:"wednesday"},{date:"10/5/2017",day:"thursday"},{date:"10/6/2017",day:"friday"},{date:"10/7/2017",day:"saturday"},{date:"10/8/2017",day:"sunday"},{date:"10/9/2017",day:"monday"},{date:"10/10/2017",day:"tuesday"}],hours=[{day:"sunday",totalHours:10,serveTimes:[{startTime:5,stopTime:15}]},{day:"monday",totalHours:10,serveTimes:[{startTime:5,stopTime:10},{startTime:15,stopTime:20}]},{day:"tuesday",totalHours:3,serveTimes:[{startTime:2,stopTime:5}]},{... ; 

const schedule = mergeByKV('day', dates, hours);
console.log(JSON.stringify(schedule, null, 2));

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

Whenever the user hits the "Enter" key, a new element will be generated and added to the bottom of an existing element

I am in need of creating a new element at the end of another element. For instance, let's say I have this element: <div id="elmtobetrig">Element that should be followed by another element when the user hits enter after this text. <! ...

Performing operations atomically within a threaded environment

Are the push and pop operations for arrays atomic? Is it safe to execute i = array.pop ... array.push(i) within a GIL-threaded environment? ...

This code encountered an Uncaught SyntaxError due to an invalid or unexpected token

Hey there, I've been struggling with an Uncaught SyntaxError: Invalid or unexpected token issue whenever I try to click on the edit or delete button. Can someone please help me figure out what's wrong with this code? I've spent hours looking ...

Error encountered in Next.js while fetching data: Invalid JSON response received, with an unexpected token "<" at the start of the JSON data

I've been attempting to utilize the getStaticProps function in order to send a request and then pass the retrieved data to a component: However, I keep encountering this error: FetchError: invalid json response body at reason: Unexpected token < ...

Creating a dynamic path to an imported file in React: A step-by-step guide

Struggling with a dilemma regarding dynamically generated paths for importing files in React. I have utilized the map() function to generate a dynamic part of the code, consisting of a repetitive sequence of div elements, each housing an audio element. The ...

Expanding and collapsing all divs with a single click using Jquery

I've gone through numerous resources but I'm still struggling to understand this concept. I have implemented a simple accordion based on this tutorial and now I want to include an "expand/collapse all" link. While I was able to expand all the ite ...

Display the component's template when invoking methods

While immersing myself in learning Vue.js, I find myself in need of some guidance. Can someone kindly review my code and point me in the right direction? Below is the code snippet along with an explanation of what I am trying to achieve. Below is the Vue. ...

Ways to integrate PHP MySQL with NodeJS and SocketIO

Currently, I am working on developing a chat application. I have successfully implemented features like creating accounts, logging in, selecting, viewing, and more using PHP MySQL. Now, I am venturing into the Instant Messaging aspect by utilizing NodeJS a ...

Can you combine multiple user validation rules with express-validator?

I have a set of rules that are almost similar, except for one where the parameter is optional and the other where it is mandatory. I need to consolidate them so that I can interchangeably use a single code for both cases. Is there a way to merge these rul ...

The jQuery script tag fails to recognize click events once dynamically loaded with the load event

Hey there, I recently utilized this script in a SAP WebDynpro setup to dynamically load and employ jQuery. The onload event of the script tag is functioning well as I can select the text of the focused element. However, I am facing issues with registering ...

Stop the background from being visible using the jQuery Cycle plugin

I'm facing a challenge with the cycle plugin for jquery when creating a slideshow. The transition between slides allows what's underneath to show, but I want a smoother transition where one slide truly fades into the other without the background ...

Caution: PHP nested array alert - string offset out of bounds

Here is the array I am working with: //This section is part of `$pins['location']` array(9) { ["address"]=> string(23) "11xxx Hudderfield xxxxxx" ["city"]=> string(12) "Jxxxxxx" ["houseNumber"]=> string(5) "11xxx" ["id"]=> NU ...

NodeJS: Implementing external URL redirection functionality

I've set up a GET /auth route that is supposed to redirect to an external resource, like https://google.com. However, instead of redirecting me to the correct URL, it redirects me to http:localhost:3000/api/auth/https://google.com. Is there a way to ...

Checking for the current loading status of a JavaScript file: How it's done

Currently, I am automating the GUI of my website using Selenium (RobotFramework). However, I have encountered an issue: Occasionally, when my automation script clicks on an element such as a button or link that is supposed to trigger an action, nothing ha ...

The fuse-sidebar elements are not being properly highlighted by Introjs

I have recently developed an angular project that utilizes the fuse-sidebar component. Additionally, I am incorporating introjs into the project. While introjs is functioning properly, it does not highlight elements contained within the fuse-sidebar. The ...

Error encountered while attempting to validate and add new entries

I am facing a challenge while attempting to insert a record into my mongodb database. Despite providing what seems to be the correct values, mongoose is flagging them as missing. Below is the Schema I am working with - var mongoose = require('mongoo ...

I am attempting to retrieve JSON data from bitbns.com, however I am encountering an issue

Being new to javascript, I recently attempted to retrieve json data from bitbns but encountered the error - "(Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘’)." I scoured the internet in search of a solution, but unfortunately ...

Use CSS specifically for codeigniter viewpage

I am unsure if it is possible, but I would like to load CSS and JavaScript within a view page instead of on include.php. Currently, the CSS file is loading on include.php and it is working correctly. What I want to achieve now is to load it directly inside ...

Route Angular 4 application static resources to a /PORT directory rather than the primary domain

Our Angular 4 application is integrated within a Node + Express app and started like a typical node app, such as: node index.js On a local machine, the Angular app is served from the /client directory: app.use(express.static(__dirname + "/client")); Onc ...

Invoke the ngrx component store's Effect in a synchronous manner

In the ComponentStore of ngrx, we have two effects. readonly startAndUpdateProgress = this.effect<void>( (trigger$) => trigger$.pipe( exhaustMap(() => this.numbersObservable.pipe( tapResponse({ next: (p ...