An efficient method for combining two arrays based on their unique identifiers without any repeated elements

Here are two arrays I need to merge:

var arrayOne = [
    {id: 10, content: '10 - dolor'},
    {id: 12, content: '12 - sit'},
    {id: 54, content: '54 - from first'}
];

var arrayTwo = [
    {id: 2, content: '2 - lorem'},
    {id: 54, content: '54 - from second'},
    {id: 80, content: '80 - ipsum'}
];

Is there a way to merge them based on id without duplicates? I attempted it using LoDash, but couldn't find a suitable solution.

The desired merged result would be:

var mergedArray = [
    {id: 10, content: '10 - dolor'},
    {id: 12, content: '12 - sit'},
    {id: 54, content: '54 - from first'},
    {id: 2, content: '2 - lorem'},
    {id: 80, content: '80 - ipsum'}
];

An efficient solution is crucial as the data source will be extensive.

Answer №1

Uncertain about its performance, you have the option to store ids in an array. If the array does not contain the id, then the current object will be added to the first array:

var ids = first.map(function (e) {
    return e.id;
});

var l = second.length;
for ( var i = 0; i < l; i++ ) {
    if (ids.indexOf(second[i].id) === -1) {
        first.push(second[i]);
        ids.push(second[i].id);
    }
} 

http://jsfiddle.net/thwny1at/

edit: EcmaScript5's Array.prototype.map is not supported in older browsers. To support those browsers, you can either use a polyfill or replace the map call with a simple for loop.

Answer №2

Check out this demonstration showcasing how to utilize various underscore methods.

_(second).each(function(si){ 
    if(!_(first).any(function(fi){ return fi.id == si.id }))
    {
        first.push(si);
    }
});

Answer №3

If you want to combine arrays using jQuery, you can utilize the extend method:

var firstArray = [1, 2, 3];
var secondArray = [1, 2, 3, 4];
var combinedArray = new Array();

$.extend(combinedArray, firstArray, secondArray);

The result will be: combinedArray [1, 2, 3, 4]

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

Is it possible for me to use ts files just like I use js files in the same manner?

So I recently stumbled upon TypeScript and found it intriguing, especially since I enjoy adding annotations in my code. The only downside is that I would have to change all my .js files to .ts files in order to fully utilize TypeScript's capabilities. ...

Transforming an HTML Attribute into a JavaScript Object

I'm encountering an issue with converting an HTML-data attribute into a JavaScript Object. Here is my approach: The data Attribute appears as: <a id="stringObj" data-string="{'Foo':'Bar'}">Some A-Tag</a> In JavaScri ...

How to Utilize Muuri Javascript Library with Bootstrap Tabs: Resizing Required for Expansion?

Struggling for days and feeling frustrated, I'm hoping someone can help me crack this mystery. My idea is straightforward - three Bootstrap 4 tabs with drag and drop functionality inside each, all displayed in a responsive stacked masonry layout. To a ...

What is the best way to showcase the information from DataProvider in Amcharts visualizations directly beneath each chart?

After creating some graphics using Amcharts, I encountered a challenge in displaying the table of data (dataProvider) right below each graph on my HTML page. Despite searching extensively for a solution, I have been unable to find one. The table of data ...

Clear Redis sorted set scores following zremrangebyscore operation

Currently, I am utilizing a Redis sorted set to maintain values in a specific order. Here is an example: score | data 0 | a 1 | b 2 | c 3 | d There are situations in my application where I need to delete certain entries. For instance, ...

Error code 400 encountered when processing Stripe webhooks

I've been working on integrating stripe webhooks into my node.js/express application, but I keep running into a 400 response from the stripe cli. Even though I followed the documentation closely and ensured that the secret key for the webhook is corre ...

Creating a Data Structure for Storing Nested Character Arrays in C

My proficiency in C is a bit rusty at the moment, which is causing me to struggle with something I believe should be quite simple. In this post, I will refer to character arrays as strings for clarity's sake. What I have is an array that can contain ...

Issue with JSON/Java not refreshing innerHTML when onClick event occurs

I'm having an issue with my JavaScript code: <script type="text/javascript"> $(document).ready(function() { $('#domaincheckbutton').click(function() { var finalMessage = document.getElementById('finalMessage'); ...

How can I combine several arrays into a multidimensional array using Swift?

Illustration let arrayOne = [a, b, c] let arrayTwo = [x, y, z] I am seeking this solution let combinedArray = [[a, b, c],[x, y, z]] I perceive two potential methods: merging both arrays (uncertain if feasible), or directly adding them to a multidimension ...

Issue with arrow functions not functioning correctly in the browser

Implementing the following method works effectively. var DBBox = React.createClass({ loadArticlesFromServer: function() { $.ajax({ url: this.props.url, dataType: 'json', data: {username:data.username,isPublished:data.isPublished, ...

Begin by checking off all checkboxes

My HTML page includes jQuery code that allows me to set all checkboxes to a 'checked' state when clicking on a 'check all' checkbox. However, I want to have all checkboxes checked by default when the page loads, without needing to click ...

The header remains fixed while scrolling - troubleshooting the If Else statement

Check out this cool pen... http://codepen.io/jareko999/pen/bZXbWP The jQuery code adds a .fixed class to the #header when it reaches or goes below 0, but doesn't remove it when back above 0. I'm new to JS and struggling to understand what' ...

The asynchronous ajax request is leading to a browser freeze

In the HTML page, I have two sets of a and p elements that are initially set to display:none. At the bottom of the page, there is a function being called with their respective ID's and values, which will enable one of them based on certain conditions ...

Issue: The registration token(s) provided for the sendToDevice() function are not valid

Currently, I am working on my final project where I am attempting to send notifications using Firebase Cloud Function when onUpdate is triggered. However, I encountered an error during the process. Despite following tutorials on YouTube and various website ...

What methods can be used to troubleshoot an issue of an AngularJS function not being called

I am facing an issue with a dynamic table I have created. The rows and action buttons are generated dynamically when the user clicks on the Devices accordion. However, there seems to be a problem with the function expandCollapseCurrent(). Whenever the use ...

Tips for expanding frisby.js by adding new "expect" functionalities?

Looking to enhance the Frisby.js module with custom expect methods without altering the source code. These extensions are tailored for my REST API to streamline common tests into a single method. An issue arises as the Frisby.js module exports its methods ...

No options displayed in AngularJS select2 dropdown

I have implemented select2 in my code following the instructions provided at https://github.com/angular-ui/ui-select2 <div ng-controller="sampleController> <select ui-select2 ng-model="select2" data-placeholder="Pick a number"> < ...

Change the background color of a webpage by clicking with the help of Javascript

I've been experimenting with a script that changes the CSS background color on click, but I'm having trouble adding a third color option. Can anyone provide guidance on how to make the third color work? Check out my jsfiddle here: https://jsfid ...

Arranging elements from an array into categories

Hey there! I woke up to an interesting challenge with the array provided below array (size=3) 0 => object(stdClass)[6] public 'id' => int 1 public 'disciplina_id' => int 3 public 'nota' => ...

Transform the dynamic JSON format into a key-value pair structure with nested children nodes

Looking to convert a dynamic JSON structure into a tree node: { "video": { "width": 1920, "height": 1080, "video_codec": "H264", "CBR": "4337025", "frame_rate& ...