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

Guide to delivering a structured JSON response with predefined data in Golang

I need to send complex data in JSON format as a response to one of my REST APIs. Here is what I have: y := "[ { \"region\":\"North America\", \"countries\":[{\"country\" : \"United States of America\",&bso ...

Locate a specific word within a sentence using PHP

Here is a snippet of code I am struggling with: $newalt = "My name is Marie"; I need to check if the words 'marie' or 'josh' appear in the above sentence: $words = array("marie", "josh"); $url_string = explode(" ", $newalt); if (!i ...

Validating Java JSON Data Types

When parsing JSON files into POJOs using Google-gson, exceptions are thrown if the JSON file does not have the correct format. However, in addition to this, type validation is needed to ensure that errors are thrown in the following cases: The types of t ...

Currently, there is a requirement to include past build outcomes in the HTML test report within the playwright

Is there a way to display the previous build status of each test case for every test case? I have been attempting to use test.info() in playwright, but it seems inaccessible from onTestEnd. One option could be to retrieve the previous build data from Jenki ...

Creating a promise in an AngularJS factory function to perform an operation

When working within an Angular factory, I am tasked with creating a function that must return a promise. Once the promise is returned, additional functionality will be added. SPApp.factory('processing', ['$http', '$rootScope&a ...

How to use jQuery to remove a class from the last entered data in a form

Reminder: This is a jQuery coding challenge, and I am required to write the validation script without using any plugins or additional modules. I have created a basic form validation script. If a user inputs data that is empty, an appropriate error message ...

Using JSON strings and the .format() method in Python3

My goal is to create a JSON string using the .format() method. However, when I attempted to do so with the code below: TODO_JSON = '{"id": {0},"title": {1},"completed:" {2}}' print(TODO_JSON.format(42, 'Some Task', False)) I encounter ...

What is the best way to distinguish between brackets in Ruby code?

My current code is designed to convert IUPAC names into structures by analyzing the user-entered string. I need to extract compound names based on brackets in the IUPAC name. Here's how I want the output to look and be stored in an array: ["(4&apos ...

When I modify the state in Vue.js, the two-way binding feature does not seem to function properly

I'm facing an issue with my dynamic array "slots" of objects which looks something like this: [{"availability": 1},{"availability": 3}] I render multiple inputs in Vue.js using v-for like so: <div v-for="slot in array"><input v-model="slot.av ...

Update the headers of the axios.create instance that is exported by Axios

I have a single api.js file that exports an instance of axios.create() by default: import axios from 'axios' import Cookies from 'js-cookie' const api = axios.create({ baseURL: process.env.VUE_APP_API_URL, timeout: 10000, headers ...

Guide to Implementing the GitHub Fetch API Polyfill

I'm facing an issue with making my code compatible with Safari by using the GitHub Fetch Polyfill for fetch(). I followed the documentation and installed it using: $ npm install whatwg-fetch --save Although I completed this step, I am unsure of how ...

Issue with extraneous event being activated upon bootstrap collapse button usage

I have implemented a functionality using Bootstrap 5.2 where I have two buttons that can hide content by utilizing the Bootstrap collapse plugin. <div class="col-12 col-sm-auto"> <span class="pe-2"> ...

Before inserting a string into JSON in PHP, the length of the string should be included

When sending a POST variable containing a JavaScript dictionary to a PHP file via Ajax, the value of this POST variable is being parsed as a PHP dictionary. However, I noticed that the length of each String value is added before the actual string in the PH ...

Shell scripting can be used to easily replace key values in a JSON file. If

Here is an example of a sample JSON file: "abc":"n", "123":"y", "atom" :"csv", After the JSON has been updated: { "abc":"try", "123":"finish", "atom" :"err", } ...

RobotFramework encounters difficulty locating an element using JavaScript

After working with RF for the past few weeks, I came across a persistent issue that has been bothering me. I keep getting the following error: The element with the locator 'XXX' (just a template) cannot be found. Upon investigating the span tha ...

Discovering the final step of a for loop when working with JavaScript objects

Currently, my data consists of: {12: Object, 13: Object, 14: Object} I need help figuring out how to detect the final iteration in the for loop below: for (var i in objs){ console.log(objs[i]); } Does anyone have any solutions? ...

Ways to reset the input field of Material UI

I'm encountering an issue with clearing a form that I created using Material UI. Despite searching for solutions on Stackoverflow, none of them seem to work for me. Using setState did not achieve the desired result of clearing the form. I am looking ...

filter array based on property value

var arr = [ {'a':1,'b':2}, {'a':1,'b':3}, {'a':1,'b':0}, ] I am looking to retrieve an array where the value of property b is 2 ...

Is JavaScript utilizing Non-blocking I/O at the operating system level to enable AJAX functionality?

Given that Javascript operates as a single threaded process and AJAX functions asynchronously, the question arises: How does this happen? Is it possible that at the operating system level, the JS engine is responsible for making non-blocking I/O calls fo ...

Utilize JQuery's .append() method to insert a new element into the DOM and then trigger an "on click" event within

I am attempting to use the .append() method to add a new radio button, and then when I click on the new radio buttons, trigger a new function. However, I am having trouble achieving this with my current code: HTML: <label>Where should the photo be ...