Utilizing JS Underscore for combining and organizing arrays with common keys

I am facing a scenario where I have two arrays:

"array_one":
[
    {
    "id": 1,
    "name": One
     },
     {
     "id": 2,
     "name": Two
     }
]

"array_two":
[
    {
    "id": 1,
    "name": Uno
     },
     {
     "id": 3,
     "name": Three
     }
]

My task involves using Underscore to achieve the following objectives:

  1. Replace all objects in array_one with objects that share the same id from array_two.

  2. Add any objects from array_two to array_one if there isn't already an object with their id present.

  3. The replaced objects should maintain their original position in the array.

  4. Any added objects need to be placed at the end of the array.

As a result, the final array should appear as follows:

"array_final":
[
    {
    "id": 1,
    "name": Uno
     },
    {
    "id": 2,
    "name": Two
     },
     {
     "id": 3,
     "name": Three
     }
]

Answer №1

var array1 = 
[
    {
    "id": 1,
    "name": 'Apple'
     },
     {
     "id": 2,
     "name": 'Banana'
     }
];

var array2 = 
[
    {
    "id": 1,
    "name": 'Manzana'
     },
     {
     "id": 3,
     "name": 'Orange'
     }
];


function compareArrays(arr1, arr2) {
  
  var tempArray = _.map(arr1, function(value) {
    var obj = _.first(_.filter(arr2, function(secondArr) { return secondArr.id === value.id; }));
    return !!obj ? obj : value;
  });
  
  return _.union(tempArray, _.filter(arr2, function(value) { return !_.some(tempArray, function(secondArr) { secondArr.id == value.id }); }));
}

var result = compareArrays(array1, array2);

console.log(result);
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Answer №2

To create two hash tables using objects, one to track added objects and another for the second array. Then, utilize reduce function to replace objects from the first array if they are found in the second array. Finally, use an additional loop to add the remaining objects from the second array.

var data = {
  "array_one": [{
    "id": 1,
    "name": 'One'
  }, {
    "id": 2,
    "name": 'Two'
  }],
  "array_two": [{
    "id": 1,
    "name": 'Uno'
  }, {
    "id": 3,
    "name": 'Three'
  }]
}

var obj = {}, added = {}
data.array_two.forEach(e => obj[e.id] = e)

var result = {finalArray: data.array_one.reduce(function(r, e) {
  r.push(obj[e.id] ? (added[e.id] = 1, obj[e.id]) : e);
  return r;
}, [])}

for(var i in obj) if(!added[obj[i].id]) result.finalArray.push(obj[i]) 

console.log(result)

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

Ways to resolve the issue of data not displaying on the page, even though it appears in the

I am attempting to upload an image that has been converted to a URL using Ajax. The issue I am facing is that $image = $_POST['imgData']; does not display anything, but when I check the developer tools in the network preview, the data can be seen ...

Instructions on how to activate scrolling for a div element that becomes visible upon clicking a button

When a button in the navbar is clicked, a div appears with a height that exceeds the viewport/page size. How can I enable scrolling for the entire page when this happens? I attempted to use overflow: scroll, but it only applied scrolling to the internal d ...

Having trouble sending a file to a web service and receiving the response in Json format?

I have a straightforward web service that requires file uploads, but I also need the response in JSON format. This poses a challenge as normally requests for JSON responses require a content-type of 'application/json', yet file uploads necessitat ...

A guide to accessing array elements (JSON) in Angular

Having a variable named $scope.informationData, the data appears like this when outputted by console.log: {"completed":100,"pending":50,"defects":20,"overdue":10} However, when trying to display just the "overdue" value in my HTML using the following cod ...

Managing Events in Angular 2 and Creating Custom Event Handlers

Currently, I am in the process of developing a component library in Angular 2 for our app teams to utilize. One of the components I recently created is a modal, but I am encountering some accessibility challenges. Specifically, I want the modal to close wh ...

Implementing an onclick function to execute a search operation

Utilizing PHP, I am dynamically populating a dropdown submenu with rows from a database. If the user wishes to edit a specific record listed in the menu, I want to enable them to do so without requiring any additional clicks. My goal is to accomplish this ...

Illuminate a corresponding regular expression within a text input

I currently have a functional code for testing regex, which highlights matching patterns. However, my challenge lies in highlighting the result within the same input as the test string. Below you will see the HTML and JavaScript snippets along with two ima ...

Error: Papa is not defined. The file was loaded from the CDN in the header section

I have integrated the cdn hosted lib for PapaParse in my HTML header. However, when I execute my JavaScript file and it reaches the function where I call Papa.unparse(data); It throws an error stating that Papa is undefined. This has left me puzzled as I h ...

Utilizing Javascript / jQuery to eliminate specific CSS styles

I am facing an issue with the CSS code for a table positioned at the bottom of the screen. The current code includes a filter specifically for IE 8, but I need to make it compatible with IE 10 as well by removing the filter and adding a background color. ...

utilize jQuery to load webpage with an HTML dropdown element

Querying the Campaigns: // Getting the campaigns $campaigns = $wpdb->get_results( "SELECT * FROM tbl_campaigns ORDER BY campaignID DESC", OBJECT_K ); // Displaying the Cam ...

The Jquery Index() method often results in a return value of -

I have developed a function in JavaScript that creates HTML content. Within the test(test1) function, I am checking if test1.Test__c is null and changing the color accordingly. The line ".table-striped > tbody > tr.testcss" is responsible for changin ...

How to prevent all boxes in jQuery from sliding up at the same time

I am encountering an issue with 36 boxes where, upon hovering over the title, the hidden text below it should slide up. However, all 36 boxes are sliding up simultaneously instead of just the one being hovered over. Below is the script I am currently using ...

Why is my JSON file turning into a folder on Firebase when I attempt to access it with Flutter?

When attempting to access my JSON file through a URL and an HTTP POST request in Firebase Storage from my emulator, it seems to transform into a folder. When I try to print the data, it gives me the contents of the folder instead of the actual file. Sa ...

Can an input element be used to showcase a chosen image on the screen?

I would like to display the selected image from an input element. Can this be done with a local file, accessing the image on the client side, or do I need to upload it to a server? Here is my React code attempt: I can retrieve the correct file name from t ...

Is the 'Document' term not recognized within expressjs?

I'm having trouble implementing a query selector in an ExpressJS application and it's not working // search products router.post('/search', function(req, res) { var db = req.db; var elasticlunr = require(&apo ...

The ternary operator is malfunctioning when it comes to the condition

I've encountered an issue while trying to integrate a custom MUI button into my project. My goal is to have the button enabled only when 2 specific objects are not empty, otherwise it should remain disabled. Despite my efforts, the code I've writ ...

Finding mongoose in an array of objects nested within another object

Here is the MongoDB JSON document I am working with: { categoryId: '1', categoryName: 'Outdoors Equipments', items: [ { itemId: '1', itemName: 'Camping T ...

Trouble with Title Updating in Next.js and Tailwind CSS Project

I am currently facing an issue with the title of my website not updating, even though I am using next/Head and have included the title tag. "use client"; import Head from 'next/head'; import { BsFillMoonStarsFill } from 'react-ico ...

Encounter the error message "Socket closure detected" upon running JSReport in the background on a RHEL system

I'm encountering an issue with JSReport at www.jsreport.net. When I run npm start --production in the background, everything seems to be working fine. But as soon as I close this session, an error pops up: Error occurred - This socket is closed. Sta ...

Utilize Content Delivery Network Components in Conjunction with a Command Line Interface Build

As we progress in building our Vue applications, we have been using the standard script tag include method for Vue. However, as we transition from jQuery/Knockout-heavy apps to more complex ones, the maintenance issues that may arise if we don't switc ...