Checking and merging arrays in Javascript

I have a unique challenge involving two arrays of objects that I need to merge while excluding any duplicates. Specifically, if an object with the key apple: 222 already exists in the first array, it should be excluded from the second array.

Please see below for the initial arrays:


var arr1 = [
    {apple: 111, tomato: 55},
    {apple: 222, tomato: 55}
]

var arr2 = [
    {apple: 222, tomato: 55},
    {apple: 333, tomato: 55}
]

The desired output should look like this:


var res = [
    {apple: 111, tomato: 55},
    {apple: 222, tomato: 55},
    {apple: 333, tomato: 55}
]

Can you guide me on how I could achieve this using JavaScript?

Answer №1

Is this solution suitable for your requirements (view demo) ?

let finalResult, index, element, previousElement;

// merging arrays
finalResult = [].concat(array1, array2);

// sorting the merged array based on the 'apple' property
finalResult.sort(function (x, y) {
    return x.apple - y.apple;
});

for (index = finalResult.length - 1; index >= 0; index--) {
    element = finalResult[index];

    // comparing each element with the previous one based on the 'apple' property
    if (previousElement && element.apple === previousElement.apple) {

        // removing elements if properties match
        finalResult.splice(index, 1);
    }
    previousElement = element;
}

Answer №2

A solution to remove duplicates can be implemented through a dedupe function.

if (!Array.prototype.dedupe) {
  Array.prototype.dedupe = function (type) {
    for (var i = 0, l = this.length - 1; i < l; i++) {
      if (this[i][type] === this[i + 1][type]) {
        this.splice(i, 1);
        i--; l--;
      }
    }
    return this;
  }
}

function combine(arr1, arr2, key) {
  return arr1
    .concat(arr2)
    .sort(function (a, b) { return a[key] - b[key]; })
    .dedupe(key);   
}

var combined = combine(arr1, arr2, 'apple');

JSFiddle Example.

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

Reinitializing AngularJS form controls

Check out this codepen example: http://codepen.io/anon/pen/EjKqbW I'm trying to reset the form elements when the user clicks on "Reset". The div elements f1,f2,f3 should be hidden and the searchText box cleared. However, the reset button is not trig ...

Observing Gulp's behavior is quite peculiar - it seems to be running

I ran into a rather peculiar issue with gulp watch. In my system, I have two disk drives: D and E. Disk D is a section of my computer's hard disk drive, while disk E is a flash drive. Both disks contain a file named test.txt: D:\test\test ...

What are the best techniques for using jQuery to manipulate an HTML form that contains nested elements?

I have a scenario where I need to dynamically generate mini-forms within an empty form based on certain conditions. For instance, imagine a form that gathers information about restaurants such as their names and locations. Depending on the number of restau ...

Tables that respond to changes in screen size, allowing nested table cells to inherit widths

I am currently working on a responsive table with unique content in each row and a concertina feature for expanding rows. When the concertina is activated, it adds another row to the table below the current row, using a td element with a colspan attribute ...

Styles in makeStyles use unique css names

Instead of using the const useStyles = makeStyles to style Popover and OtherStyles separately, I want to nest them within Popover, like so: const useStyles = makeStyles({ Popover: { root: { textAlign: "center", ...

Retrieve specific JSON information

Below is an example of JSON data: [{ "RM_Name": "Russ Martin", "Division": "East", "RM_Phone": "(603) 491-1259", "RC_Name": "Jacob Sucoff", "RC_Phone": "(800) 247-4154 x3403", "States_Covered": "MT,VT, NH, ME (all firms)", "La ...

Mastering MongoDB update functions in JavaScript

I've encountered some difficulties while using the MongoDB API to update a document. Despite trying various methods, none of them have been successful so far. Strangely enough, inserting and deleting documents work perfectly fine. Let me explain what ...

Upon initialization, navigate to the specified location in the route by scrolling

My page has various components stacked one after the other, such as: <about></about> <contact></contact> I am utilizing the ng2-page-scroll to smoothly scroll to a particular section when a navigation link is clicked. However, I a ...

What is the process for defining custom properties for RequestHandler in Express.js middleware functions?

In my express application, I have implemented an error handling middleware that handles errors as follows: export const errorMiddleware = (app: Application): void => { // If the route is not correct app.use(((req, res, next): void => { const ...

Stop the click event using a confirmation dialog before proceeding with the operation

I'm trying to implement a confirmation dialog before deletion by using e.preventDefault() to prevent immediate deletion. However, I am facing an issue in the YES function where I would like to resume the click event's operation with return true w ...

What steps do I need to take to retrieve my paginated data from FaunaDB in a React frontend application?

I am facing a challenge when trying to access the data object that contains the keys (letter and extra) in my response from the faunadb database to the frontend react. Although I have used the map function in my frontend code, I have not been successful ...

Utilizing React Material UI for form validation with error handling and informative helper text

I recently created a form in which I needed to validate the inputs. During my research, I came across the material UI library that has an attribute called error boolean, and another attribute called helperText for the TextField input of the form. However ...

What could be the reason my mat-form-field is not displaying the label?

I'm currently working on a project using Angular Material to build a web page. I am facing an issue with the mat-form-field component as the label is not displaying, and I can't figure out why. Any assistance would be greatly appreciated. Thank y ...

Do I need to provide my email and password while using the Firebase signInWithGoogle()?

After attaching the signInWithGoogle() method to a button within the form, instead of opening a popup window as expected, it prompts me to fill in the email and password fields. Below is the configuration file: import firebase from 'firebase/app' ...

Jade console.log() not functioning properly as anticipated

Is it possible that I can just insert -console.log('hello') into any part of the jade code? It doesn't seem to be working, do you know what could be causing this issue? ...

Maintain the state of various panels on page load with the Bootstrap Accordion feature

I have implemented a Bootstrap accordion on my form page which allows users to open multiple panels simultaneously. Upon submitting the form, I want to preserve the state of any open Bootstrap accordion panels. To achieve this, I utilized code from stack ...

on clicking GTM, obtain a different child element

My HTML code is structured as follows: <div onclick="location.href='https://ford-parts-accessories.myshopify.com/products/ash-cup-coin-holder-with-lighter-element?refSrc=6748959244479&amp;nosto=productpage-nosto-1-fallback-nosto-1';&q ...

Custom pagination with onSelectionModelChange in React Material UI Data Grid

Has anyone encountered a problem with using the DataGrid component's onSelectionModelChange prop? I can successfully retrieve the selected rows for a single page, but when I implement custom pagination and navigate to the next page, the previous selec ...

The jQuery function fails to execute when the script source is included in the head of the document

I'm relatively new to working with scripts and sources, assuming I could easily add them to the header and then include multiple scripts or functions afterwards. Everything seemed to be working fine at first, but now I've encountered a problem th ...

While attempting to run the project I downloaded from GitHub using the command npm run serve, I encountered the following error: "Syntax Error: Error: No ESLint configuration found in

After receiving a Vue.js project from GitHub, I attempted to download and run it. However, when I tried the command npm run serve, I encountered an error message: Syntax Error: Error: No ESLint configuration found in C:\Users\User\Desktop&bs ...