Merge two arrays of objects with underscore functions

Here are two arrays of objects that I have:

var x = [{id:456, name:'falcon'},
         {id:751, name:'gagarin'},
         {id:56, name:'galileo'}]

var y = [{id:751, weight:6700},
         {id:456, weight:2958},
         {id:56, weight:7200}]

With the help of underscorejs, how can we merge array x with array y to create a new array z which includes the weight property from array y where the id matches:

var z = [{id:456, name:'falcon', weight:2958},
         {id:751, name:'gagarin', weight:6700},
         {id:56, name:'galileo', weight:7200}]

Answer №1

A method using underscore is demonstrated below:

var result = _.map(array, function(item) {
    var data = _.findWhere(anotherArray, { id: item.id });

    return _.extend(item, data);
});

To experiment with this method further: http://jsfiddle.net/b90pyxjq/3/

Answer №2

To merge objects in list a and list b, you can use the _.map function to map each object, the _.indexBy function to index them, and the _.extend function to create a list of merged objects.

This solution makes use of the Underscore.js library, which can be found at this link.

var a = [
  { id: 456, name: 'sojuz' },
  { id: 751, name: 'sputnik' },
  { id: 56,  name: 'arianne' }
];

var b = [
  { id: 751, weight: 5800 },
  { id: 456, weight: 2659 },
  { id: 56,  weight: 6700 }
];

function mergeLists(listA, listB, idField) {
  var indexA = _.indexBy(a, idField)
  var indexB = _.indexBy(b, idField);

  return _.map(indexA, function(obj, key) {
    return _.extend(obj, indexB[key]);
  });
}

var c = mergeLists(a, b, 'id');

document.body.innerHTML = JSON.stringify(c, null, ' ');
body {
  white-space: pre;
  font-family: monospace;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Edit

In an updated version of the example above, unnecessary indexing of the a list has been removed for increased efficiency. This revised solution outperforms Aurélien Thieriot's solution by approximately 48% in terms of speed.

For a demonstration, refer to this link.

function mergeLists3(listA, listB, idField) {
  var indexB = _.indexBy(listB, idField);

  return _.map(listA, function(obj, key) {
    return _.extend(obj, indexB[obj[idField]]);
  });
}

Answer №3

This implementation is functional but not efficient:

let finalArray = [];
for(let i = 0; i < firstArray.length; i++) {
   for (let j = 0; j < secondArray.length; j++) {
      if(secondArray[j].id == firstArray[i].id) {
        let newObj = {
          id: firstArray[i].id,
          name: firstArray[i].name,
          weight: secondArray[j].weight
        }
        finalArray.push(newObj);
        break;
      }
   }
}

Although this approach has a time complexity of O(n^2), there are ways to optimize it further.

Answer №4

Employ ES6 or utilize polyfilled replacements in ES5 to extract property names without underscores:

a.map(function (aItem) {
    var matched = b.find(function (bItem) {
        if (aItem.id == bItem.id) return true;
    }) || {};

    Object.getOwnPropertyNames(matched).map (function (property) {
        aItem[property] = found[property];
    });
});

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

Tips for handling datetime in angular

Currently, I am working with Angular (v5) and facing an issue related to Datetime manipulation. I am trying to retrieve the current time and store it in a variable. After that, I need to subtract a specified number of hours (either 8 hours or just 1 hour) ...

Webpack and terser reveal the names of the source files in the compressed output

Is there a way to stop source filenames from appearing in webpack output even when using Terser for minification? Illustration After minifying my production React app build, the resulting .js output file still contains original source filenames rather th ...

Updating variable storage in React components

This is a project built with Next.js and React. Below is the folder structure: components > Navbar.js pages > index.js (/ route)(includes Navbar) > submitCollection.js (/submitCollection)(includes Navbar) The goal is to allow users to inpu ...

Encountering a 405 error when attempting to send a request through an express route in a Next

After deploying my Express js routes in Next js on hosting, I encountered an error 405 when sending requests to the route. However, everything works fine when I test it on localhost. I'm puzzled by this issue. Can anyone help me understand what' ...

Using an AngularJS directive to trigger a function with ng-click

Everything is working well with my directive, but I would like to utilize it within ng-click. Unfortunately, the function inside the link is not getting triggered. Here's the link to the code snippet. <div ng-app="editer" ng-controller="myCtrl" ...

Utilizing JQUERY and AJAX for conditional statements

I am currently in the process of creating a basic chat bot. At this point, the bot replies when the user inputs a pre-defined question. However, I am trying to figure out how to program the chatbot to respond with a "sorry, I don't understand" message ...

Load jQuery script after Ajax call has loaded the filter

Currently, I have multiple jQuery scripts running on one page. This specific page includes a product filter that operates using ajax. You can view the product filter at Below is one of the scripts I am utilizing: var $s = jQuery.noConflict(); $s('bo ...

Adding up the values of an array of objects by month using ReactJS

To start off, I'm using ChartJS and need to create an array of months. Here's how it looks: const [generatedMonths, setGeneratedMonths] = useState<string[]>([]) const [totalValues, setTotalValues] = useState<number[]>([]) const month ...

Sorting the array in MongoDB before slicing it

Currently, I have a pipeline that aggregates Regions along with their respective countries and sales values. My goal is to obtain the top 5 countries by sales in each region using the $slice method. However, the issue I am facing is that it returns the fir ...

Importing data from an external file into an array using AngularJS

Hey there, I'm new here on Stack and hoping someone can lend a hand because I've hit a roadblock! I'm working with an AngularJS script that generates multiple icons using data from a simple array. Each icon is linked to a YouTube video. Th ...

What is the best way to accurately determine the height and offset values of an element while utilizing ng-repeat?

My objective is to determine the offset and height of list items. Once I have those values, I trigger a function in a parent directive. Ultimately, this will involve transitioning elements in and out as they come into view. Issue: Due to the use of ng-rep ...

When implementing AngularJS in a situation where the page layout is created by the user, what is the best

As I work on developing a web application, my main goal is to incorporate around 6 unique "widgets" that users can interact with. These widgets will serve different functions and users will have the ability to add, remove, and position them as they wish on ...

Error: Unable to locate Buffer2

I encountered the error Uncaught TypeError: Buffer2 is undefined when trying to import jsonwebtoken into my React project. The errors occur with both import jwt from jsonwebtoken and import {decode} from 'jsonwebtoken'. My versions are jsonwebt ...

An unconventional web address was created when utilizing window.location.hostname

I've encountered an issue while trying to concatenate a URL, resulting in unexpected output. Below you'll find the code I tested along with its results. As I am currently testing on a local server, the desired request URL is http://127.0.0.1:800 ...

Is it typical to experience a forced reflow violation and page offset?

After implementing a position: fixed on-scroll feature for my navbar, I noticed an error being thrown by the DOM stating: [Violation] Forced reflow while executing JavaScript took ms during every scroll event. It seems that this could be caused by layout t ...

Object.assign changes the original array object in place

I am facing a challenge while attempting to modify the value of a specific index in my state, specifically the property post_comments. The issue lies in the fact that even though I am only modifying a copy of the state, the actual state is also being alter ...

Why is the JavaScript function loaded through Ajax not running as expected?

I manage several websites with identical data protection policies. To streamline the process, I've created a file on a separate server that can be accessed through Ajax integration. One crucial aspect is the ability to set an opt-out option and store ...

Displaying numerous pointers on Google Maps by utilizing PHP arrays that are populated with information extracted from a MySQL database

I'm new to stack overflow and seeking some help. I have two PHP arrays storing latitude and longitude values based on user input. Using a basic Google Maps API tutorial map, how can I add multiple markers using only the latitude and longitude from th ...

What is the best way to display HTML using Highlight.js in a Vue component?

I'm working on incorporating highlight JS into my Vue project, and I am looking to display a div on the edges of my code. I've experimented with the following: <pre v-highlightjs="viewerHTML"><div>Something here</div><code c ...

Is your preference selecting made a breeze by dragging the input field?

Looking to create a form that allows users to indicate their preference between Option A and Option B by dragging a slider. I know there must be a library out there that already does this, but I can't seem to figure out what it's called to searc ...