Creating a single array of objects from two separate arrays of objects that share a common key in JavaScript

My task at hand involves merging two arrays of objects retrieved from different REST API calls. The structure of the arrays is as follows: [{date: date, name: name}, ...]. Let's refer to them as Array A and Array B.

If both Array A and Array B contain objects with the same date, the final array should look like this:

[{date: date, nameA: nameA, nameB: nameB}]

If there are no matching dates, simply insert an object like this: [{date: dateA, nameA: nameA}]

For example:

Array A = [
    {
      date: 2017-01-01, 
      name: 'New Year Eve'
    },
    {
      date: 2017-02-02, 
      name: 'feb2'
    }
]

Array B = [
    {
      date: 2017-01-01, 
      name: 'New Year Eve'
    },
    {
      date: 2017-03-03, 
      name: 'march3'
    }
]

The final merged array would be:

finalArray = [{
    date: 2017 - 01 - 01,
    nameA: 'New Year Eve',
    nameB: 'New Year Eve'
},
{
    date: 2017 - 02 - 02,
    nameA: 'feb2'
},
{
    date: 2017 - 03 - 03,
    nameB: 'march3'
}

]In this scenario, objects with the same date may appear in different positions within the array, making simple checks like:

arrayA[0].date === arrayB[0].date

Answer №1

To efficiently handle objects with the same date, consider using a hash table.

var arrayOne = [{ date: '2017-01-01', name: 'New Year Eve' }, { date: '2017-02-02', name: 'feb2' }],
    arrayTwo = [{ date: '2017-01-01', name: 'New Year Eve' }, { date: '2017-03-03', name: 'march3' }],
    mergedResult = function mergeArrays(arrays, names) {
        var hashList = Object.create(null),
            resultArray = [];

        arrays.forEach(function (arr, index) {
            arr.forEach(function (obj) {
                if (!hashList[obj.date]) {
                    hashList[obj.date] = { date: obj.date };
                    resultArray.push(hashList[obj.date]);
                }
                hashList[obj.date][names[index]] = obj.name;
            });
        });
        return resultArray;
    }([arrayOne, arrayTwo], ['nameOne', 'nameTwo']);

console.log(mergedResult);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

 let newArr = [];
for (let x = 0; x < firstArr.length; x++) {
    for (let y = 0; y < secondArr.length; y++) {
        if (firstArr[x].date == secondArr[y].date) {

            //push to the new array if date does not exist
        }
    }
}

Answer №3

Discover the power of Array.prototype.concat(), a function designed to combine two or more arrays effortlessly. Here's an example:

finalArray = arrayA.concat(arrayB)

After creating finalArray, the next step involves iterating through it, eliminating any duplicate dates by merging their attributes together. Check out the code snippet below for implementation:

for (var i = 0; i < finalArray.length; i++) {
    if (finalArray[i]["date"] === finalArray[i+1]["date"]){
        finalArray[i]["nameA"] = finalArray[i]["name"];
        finalArray[i]["nameB"] = finalArray[i+1]["name"];
        // Remove the repeated entry
        delete finalArray[i+1][key]
    }
}

Give it a try and see how it works!

Answer №4

To determine the combined array length, you can utilize the Array.from method and subtract the length of the arrays accordingly.

var arrayA = [{date: '2017-01-01', name: 'New Year Eve'},{date: '2017-02-02', name: 'feb2'}];
var arrayB = [{date: '2017-01-01', name: 'New Year Eve'},{date: '2017-03-03',name: 'march3'}];

var arr= Array.from(new Array(arrayA.length+arrayB.length),(x,y)=> arrayB[y]||arrayA[y-arrayA.length]);
console.log(arr);

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

Having difficulty implementing interval to a maximum of 2 minutes or until a certain condition is fulfilled in Angular

In my current scenario, I am working with two APIs - apiOne and apiTwo. When I call apiOne, it should return a response. If the response is successful, then I need to pass this response as a parameter to apiTwo. ApiTwo will then provide another response wh ...

Can I bypass an invalid SSL certificate when making a request using a JavaScript library?

Is it possible to bypass invalid SSL certificates when using the widely-used request library? You can find more information about the library here: https://www.npmjs.com/package/request I am currently integrating this library into a Node.js server to send ...

Uploading a CSV file in JSON format to Amazon S3 with Node.js

Within my nodejs server.js script, the following code snippet can be found: router.post('/submission', (req, res) => { let data_filtered = req.body.data }) Upon user submission of a csv file, I am successfully retrieving it on the backend. ...

Determine the percentage variance for each item within an array and showcase it in a data table using Vue Vuetify

My data source is a JSON file structured as follows: {"USD": {"7d": 32053.72, "30d": 33194.68, "24h": 31370.42}, "AUD": {"7d": 43134.11, "30d": 44219.00, "24h": 42701.11}, &quo ...

Interactive HTML Table - Capture Modified Fields

I currently have an HTML table that I am working with. The structure of the table is as follows: <table style="width:100%"> <tr> <th>id</th> <th>Lastname</th> <th>Age</th> </tr> <t ...

Incorporate SVG files into a TypeScript React application using Webpack

I am trying to incorporate an SVG image into a small React application built with TypeScript and bundled using Webpack. However, I am encountering an issue where the image is not displaying properly (only showing the browser's default image for when n ...

How can I use node.js to send an API response in the body?

I have successfully implemented an API that is providing the desired response. However, I am now looking to set this response directly into the body section. Currently, the response is being displayed within a <pre> tag on the website as shown below ...

JQuery horizontal navbar hover animations

Looking to design a simple navigation bar that displays a submenu when hovering over a link. The issue I'm facing is that the submenu disappears when moving from the link to the submenu itself, which is not the desired behavior. How can this be fixed ...

Determine the location of an element within a scrolling container using jQuery and automatically scroll to that location

Hey there! I've got a list of items (users) in a popup that's contained within a scrollable div. What I'm trying to achieve is creating a search box using jQuery and Javascript to determine the position of a specific user in this list and th ...

Generating a 3D path using latitude and longitude coordinates in Three.js

Looking to create a pipe-like structure based on geographic coordinates, the data is in JSON format with latitude and longitude values. Here's an example of how it looks: [ { "LATITUDE": "55.10185525", "LONGITUDE": "-76.4629527" }, { "LAT ...

Implementing the DRY (Don't Repeat Yourself) principle across a group of related

I'm struggling with applying the DRY principle. Can someone assist me in creating a single function that can achieve the same results as these 4 functions? I also need guidance on how to call this function for each .symbol. function changeGradient(in ...

script locate the div ID within a given text and clear its content

My string contains some dynamic HTML with a div element having an id of "time", Here's an example: myString = "<div class="class">blahblah</div><div id="time">1:44</div>" How can I generate a new string that is identical to ...

What is the process of declaring a variable within a Vue template?

Issue I find myself in a situation where I must temporarily hold the output of a function call in Vue templates. This is a common scenario within loops, especially when computed properties are not easily applicable. <ul> <li v-for="vehicleType ...

Arrays of characters in Fortran

I am seeking a method to handle a set of character data using two simultaneous arrays within the same program unit. For instance, I envision CHARACTER(1) Array1(40960) and CHARACTER(4096) Array2(10) both referencing the same data. It's worth not ...

Are $.ajax() callback functions not tied to the requests they originate from?

The code is quite intricate, so I have simplified it below in order to verify whether the behavior I am encountering is normal or if there is some other error I have introduced into the code. I have two distinct ajax requests, each with its own unique cal ...

How can I send a JavaScript variable to a PHP function using an Ajax call?

I'm having trouble implementing an AJAX search form in WordPress that retrieves posts based on the search term being present in the post title. Below is the PHP function I've created for this purpose: function get_records_ajax($query) { $arg ...

What is the method for sending the selected value from a dropdown menu instead of the HTML text within it via an Ajax post request?

I am in the process of developing a webpage that requires sending post data using Ajax (JQuery). Below is the (most relevant) snippet of HTML code: <div class="command-list"> <form action="app_page.php" method="post"> <select name="T ...

What is the best way to incorporate multiple functions within a React button?

I need to implement a functionality where the startClick function is triggered on BackButton click before executing the dispatch (giveForm2PreviousStep(props.currentStep, props.goToStep)) method. How can this be achieved? Inquiry JS const Inquiry = props ...

Exploring Cross Origin Policy Restrictions with Fiddler for JSON Debugging

In the process of creating a modern webapp using JSON data, I came across a helpful blog post about using Fiddler to mock JSON data. My development setup involves working locally with Notepad++ and testing primarily on Chrome, with plans to expand to othe ...

Add a new element to an array in a PHP file that will then output the modified

I am faced with a task involving a file that is structured like this: <?php return [ 'key1' => 'value1', 'key2' => 'value2', ... ]; The requirement is to add an additional array entry to this f ...