Tips for merging two arrays in a 2-dimensional array using lodash

Suppose I have an array of messages structured like this:

[{
    day: "1",
    msgs: [{day: "1", id: 1, msg: 'txt'}]
},{
    day: "2",
    msgs: [{day: "2", id: 2, msg: 'txt'}]
}]

Now, new messages are received from the server in the following format:

[
    {day: "1", id: 3, msg: 'txt'},
    {day: "1", id: 4, msg: 'txt'},
    {day: "2", id: 5, msg: 'txt'},
    {day: "3", id: 6, msg: 'txt'}
]

The task at hand is to merge these new values into the existing messages array. The desired outcome should resemble the example below:

[{
    day: "1",
    msgs: [{day: "1", id: 1, msg: 'txt'},
       {day: "1", id: 3, msg: 'txt'},
       {day: "1", id: 4, msg: 'txt'}]
},{
    day: "2",
    msgs: [{day: "2", id: 2, msg: 'txt'},
       {day: "2", id: 5, msg: 'txt'}]
},{
    day: "3",
    msgs: [{day: "3", id: 6, msg: 'txt'}]
}]

I've spent hours searching on stack overflow for a similar scenario but couldn't find one. I attempted using lodash functions like groupBy and forEach, but unfortunately, none of them worked as expected. The crucial requirement is that if a NEW DAY is introduced by the server, it should be added to the existing results.

Answer №1

It appears that the data format you requested contains a considerable amount of redundant information. In light of this, I would like to suggest adjusting your code to utilize the following data format:

var data = [{day: "1", id: 3, msg: 'txt'},
            {day: "1", id: 4, msg: 'txt'},
            {day: "2", id: 5, msg: 'txt'},
            {day: "3", id: 6, msg: 'txt'}
           ],
dailyMsg = data.reduce((dm,obj) => dm[obj.day] !== void 0 ? (dm[obj.day] = dm[obj.day].concat({id: obj.id, msg: obj.msg}),dm)
                                                          : (dm[obj.day] = [{id: obj.id, msg: obj.msg}],dm),{});
console.log(dailyMsg);

Answer №2

If you want to achieve this using native JavaScript, you can utilize the forEach() and find() methods.

var originalArray = [{
    day: "1",
    msgs: [{day: "1", id: 1, msg: 'txt'}]
},{
    day: "2",
    msgs: [{day: "2", id: 2, msg: 'txt'}]
}];

var newArray = [
    {day: "1", id: 3, msg: 'txt'},
    {day: "1", id: 4, msg: 'txt'},
    {day: "2", id: 5, msg: 'txt'},
    {day: "3", id: 6, msg: 'txt'}
];

newArray.forEach(function(obj) {
  var element = originalArray.find((a) => a.day == obj.day);
  (element != undefined) ? element.msgs.push(obj) : originalArray.push({day: obj.day, msgs: [obj]});
})

console.log(originalArray)

Answer №3

To combine two arrays, you can simply follow the steps below. Using the .concat method will help merge the two arrays together.

    var firstArray = [{
        day: "1",
        msgs: [{day: "1", id: 1, msg: 'txt'}]
    },{
        day: "2",
        msgs: [{day: "2", id: 2, msg: 'txt'}]
    }];

      var secondArray = [
        {day: "1", id: 3, msg: 'txt'},
        {day: "1", id: 4, msg: 'txt'},
        {day: "2", id: 5, msg: 'txt'},
        {day: "3", id: 6, msg: 'txt'}
    ];

var combinedArray = firstArray.concat(secondArray);

Answer №4

Personally, I believe Nenad Vracar's approach is superior, especially if ECMAScript 6 is supported.

Unlike my solution, Vracar's method does not rely on ECMAScript 6 features.

var oldMessages = [
    {
        day: "1",
        msgs: [{day: "1", id: 1, msg: 'txt'}]
    },
    {
        day: "2",
        msgs: [{day: "2", id: 2, msg: 'txt'}]
    }];
    
    var newMessages = [
        {day: "1", id: 3, msg: 'txt'},
        {day: "1", id: 4, msg: 'txt'},
        {day: "2", id: 5, msg: 'txt'},
        {day: "3", id: 6, msg: 'txt'}
    ];
    
    function merge(oldMessages, newMessages) {
      for (var i=0; i<newMessages.length; i++) {
        var exists = false;
        for (var j=0; j<oldMessages.length; j++) {
        if (oldMessages[j].day == newMessages[i].day) {
          oldMessages[j].msgs.push(newMessages[i]);
            exists=true;
            break;
          }
        }
        if (!exists) {
        oldMessages.push({'day':newMessages[i].day,'msgs':newMessages[i]});
        }
      }
      return oldMessages;
    }
    
    console.log(merge(oldMessages, newMessages));

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

How can you display select elements from an array in Smalltalk?

Currently, I am developing a beginner's small talk program with the objective of displaying all elements of an integer array forwards and backwards. Additionally, I intend to print only those array elements that end with a specific digit. Although I ...

Creating a JavaScript script to implement a CAPTCHA feature on Google Forms

I'm looking to implement a JavaScript solution that can prevent spam on Google Forms. The idea is as follows: Generate a random number a between 1 and 1000; Generate another random number b between 1 and 1000; Obtain input from the user, storing it a ...

Maintain the previous interval even after resetting setInterval

In my application, I have a feature that checks for sports events every 5 hours. If no sporting events are found, the interval changes to 1 hour. To keep things concise and relevant, I've removed unnecessary parts from the file since it's quite l ...

"Encountered a 'NextAuth expression cannot be called' error

Recently, I delved into learning about authentication in Next.js using next-auth. Following the documentation diligently, I ended up with my app/api/auth/[...nextauth]/route.ts code snippet below: import NextAuth, { type NextAuthOptions } from "next-a ...

What is the process for obtaining a direct link to a file that has been uploaded using a

Can Google Apps Script provide a direct link to a file that has been uploaded to a Google Drive folder? Currently, I can only obtain a link to the folder itself where all files are saved. This is the code I am using for file uploads: function processFor ...

The incorrect rendering result in Three.js

Having an issue with my basic three.js code. It is set up to display a few cubes, but some of the background cubes are showing in front. Could I have missed something? You can view the code at (use shift to rotate the camera). Any assistance would be m ...

Convert the HTML content into a PDF while retaining the CSS styles using either JavaScript or Django

Looking to create a PDF of an HTML element with background color and images. Seeking a solution, either client-side or server-side using Django/Python. Tried jsPDF on the client side, but it does not support CSS. Considering ReportLab for Django, but uns ...

Implement a Bootstrap accordion onto a webpage seamlessly alongside an outdated jQuery version to avoid any conflicts

My bootstrap accordion is not functioning properly, the animation seems to be broken. How can I fix it? I suspect that it might be due to using an outdated version of jQuery or because the theme developers implemented a custom solution. The end result is ...

Using React to retrieve information from an array stored in the state

Hello there, I'm currently learning React and I'm facing an issue with my code. Within my state, I have an array and a function called submitted. This function is used to push new data into the array. Everything seems to be working fine except f ...

Looking for an alternative method to replace the nested forEach loops for iterating over a single array

I have an array that consists of multiple arrays and in order to access the objects within, I have utilized multiple forEach loops. How can I manage this situation without chaining the forEach methods? Please provide an alternative approach to enhance the ...

The issue with running commands in parallel using npm remains unresolved

Within my project folder, I have a package.json file located at the root directory. This JSON file contains separate client and server folders. In the main package.json file, I have defined the following scripts: "scripts": { "server&quo ...

Determine the value of an object by iterating through its keys

UPDATE: (for clarification) I currently have a table named modelCoa +----+----------+-------+--------------------+ | id | id_parent| code | name | +----+----------+-------+--------------------+ | 1 | 0 | 1 | asset ...

Error: Unable to access attributes of null object (specifically 'accessToken')

After following a YouTube tutorial by Lama for creating an E-commerce application, I attempted to add a logout feature on the admin page that was not covered in the tutorial. To implement this, I used Redux to grab the currentUser and set it to null to suc ...

Encountering a JavaScript runtime error while trying to access and interpret JSON

Currently, I'm facing a challenge with converting a C# list of string types into a JSON object. The issue arises when trying to read this JSON object later in JavaScript. On the other hand, the process seems to work fine when dealing with a C# list of ...

The error message "the property '_env_' is not found on the type 'Window & typeof globalThis - React / Typescript ERROR" indicates that the specified property is not present in the

I encountered an issue while working with React/TypeScript. When I perform this action within the component: <p>API_URL: {window._env_.API_URL}</p> The error message I receive is: property '_env_' does not exist on type 'Window ...

PHP multi-array saving causes alteration of string values

I am retrieving data from a database and saving the date and hour strings in an array: $array_likes_Days=$wpdb->get_results("SELECT time , totalLikesDay FROM pstableliker WHERE likeUrl='".$url_selec."' AND totalLikesDay !=0 ;"); $arrayDateH ...

Can you please explain the meaning of "!" in JavaScript as it pertains to my explanation?

I comprehend how the exclamation mark is used in code such as != or !==, but I am curious about its meaning when it precedes something like if(!arr[i]){"do this} Appreciate your response. ...

New toggle button for Twitter Bootstrap 3 navbar featuring unique icon symbol

Looking to enhance my mobile navigation using Twitter Bootstrap 3 by adding an additional navbar. The navbar will feature two toggle buttons on each side - the left button will have the classic "three bar" icon, while the right button will have a differen ...

Retrieve Latitude and Longitude by clicking using JavaScript

When I click on the map, I want to retrieve the latitude and longitude coordinates and display them in an alert. Here is the code I have: <!DOCTYPE html> <html> <body> <div id="googleMap" style="width:100%;height:400px;"></div&g ...

Interactive table with Draggable feature supported by Bootstrap Vue

After tirelessly searching for a solution to drag and drop rows on a Bootstrap Vue table, I finally stumbled upon a functional version here: Codepen I attempted to integrate this code into my own table: Template: <b-table v-sortable="sortableOptions ...