What is the best way to filter out and combine one array from two arrays in lodash based on their unique properties?

Lodash v 4.17.15

Consider the scenario where two arrays are involved:

var users = [{
      id: 12,
      name: Adam
   },{
      id: 14,
      name: Bob
   },{
      id: 16,
      name: Charlie
   },{
      id: 18,
      name: David
   }
]


var jobs = [{
      empid: 12,
      profession: Engineer
   },{
      empid: 14,
      profession: CEO
   },{
      empid: 16,
      profession: CFO
   },{
      empid: 18,
      profession: CTO
   }
]

Desired Outcome

var jobsEmp= [{
          empid: 12,
          id: 12,
          name: Adam
          profession: Engineer
       },{
          empid: 14,
          id: 14,
          name: Bob
          profession: CEO
       },{
          empid: 16,
         id: 16,
          name: Charlie
          profession: CFO
       },{
          empid: 18,
          id: 18,
          name: David
          profession: CTO
       }
    ]

The typical approach is to :

var jobsEmp =  _.forEach(users, function (emp) {
                    emp.jobs = _.find(jobs, function (jb) {
                        return jb.empid === emp.id;
                    });
                });

However, this method may not be optimal. After reviewing the documentation extensively, it remains unclear on what technique is the most efficient and how to achieve this effectively using lodash.

Answer №1

Opting for a method that enhances readability is key when working on code with your team. Choose what works best for you and ensures clarity.

const _ = require('lodash')

const users = [{
      id: 12,
      name: 'Adam'
   },{
      id: 14,
      name: 'Bob'
   },{
      id: 16,
      name: 'Charlie'
   },{
      id: 18,
      name: 'David'
   }
]


const jobs = [{
      empid: 12,
      profession: 'Engineer'
   },{
      empid: 14,
      profession: 'CEO'
   },{
      empid: 16,
      profession: 'CFO'
   },{
      empid: 18,
      profession: 'CTO'
   }
]

const merged = _.merge(_.keyBy(users, 'id'), _.keyBy(jobs, 'empid'));
const values = _.values(merged);
console.log(values);

output

[ { id: 12, name: 'Adam', empid: 12, profession: 'Engineer' },
  { id: 14, name: 'Bob', empid: 14, profession: 'CEO' },
  { id: 16, name: 'Charlie', empid: 16, profession: 'CFO' },
  { id: 18, name: 'David', empid: 18, profession: 'CTO' } ]

Answer №2

Not relying on lodash:

const users = [{
  id: 12,
  name: "Adam"
}, {
  id: 14,
  name: "Bob"
}, {
  id: 16,
  name: "Charlie"
}, {
  id: 18,
  name: "David"
}];


const jobs = [{
  empid: 12,
  profession: "Engineer"
}, {
  empid: 14,
  profession: "CEO"
}, {
  empid: 16,
  profession: "CFO"
}, {
  empid: 18,
  profession: "CTO"
}];

const result = users.map((user) => {
  const job = jobs.find((job) => job.empid === user.id);

  return Object.assign({}, user, job);
});

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

Why is it that I am unable to properly encode this URL in node.js?

$node querystring = require('querystring') var dict = { 'q': 'what\'s up' }; var url = 'http://google.com/?q=' + querystring.stringify(dict); url = encodeURIComponent(url); console.log(url); Here is the re ...

After using browserify, when attempting to call the function in the browser, an Uncaught ReferenceError occurs

I am currently in the process of creating a compact NPM package. Here is a basic prototype: function bar() { return 'bar'; } module.exports = bar; This package is meant to be compatible with web browsers as well. To achieve this, I have inst ...

Query parameter is not defined

Can anyone assist me with extracting the ean from the following URL: This NodeJS server processes the request in the following manner: const http = require('http') const port = 3000 const requestHandler = async (request, response) => { ...

Removing a value from a JSON object by utilizing the .map function

My JSON object is structured as follows: [{"box":1,"parent":[],"child":[{"boxId":2},{"boxId":3}]},{"box":2,"parent":[{"boxId":1}],"child":[]}] I am attempting to remove the element "child":[{"boxId":2} with boxId=2 from the object. I have tried using a , ...

When trying to append in jQuery, the error "JQuery V[g].exec is not a

Attempting to create a script that adds a table to a div within the website using the following function: function generateTable(container, data) { var table = $("<table/>"); $.each(data, function (rowIndex, r) { var row = $("<tr/>"); ...

Console is displaying an error message stating that the $http.post function is returning

Just diving into angular and I've set up a controller to fetch data from a factory that's loaded with an $http.get method connecting to a RESTful API: videoModule.factory('myFactory', function($http){ var factory = {}; facto ...

Non-reactive arrays in Vue.js

I am facing an issue. Here is the problem: data: { tracks: [] } The tracks array will contain a complex object. I want to achieve reactivity when assigning a new value to tracks nested object, but I do not need deep reactivity for the object. ...

Excluding certain source files in Typescript's tsconfig is a common practice to

My attempt to configure Typescript to exclude specific files during compilation is not working as expected. Despite setting exclusions in my tsconfig.json file, the code from one of the excluded files (subClassA.ts) is still being included in the compiled ...

The for loop unexpectedly interrupts a different array

Hey there, I've been working with puppeteer and came across an issue with the following code snippet: console.log(dealsId[i]); for (var i = 0; i < sizes.length; i++) { var refIdClasses = await sizes[i].$eval('input', a => a.getAtt ...

What is the best way to integrate a button within a datatable cell to display additional details in a popup window?

I am seeking help with datatable.js. I would like to insert a button inside the cells of the datatable columns to expand and display the detailed content of each cell. When I click on the red button, a popup modal should appear showing the full list of con ...

Unlocking the Count of ng-repeat Elements in Angular JS 1

I'm curious about how to obtain the count of items in ng-repeat using AngularJS. In this particular code, I'm interested in finding out the count of "skill" because I want to set a limit on it. If the count of skills exceeds 5, I only want to dis ...

Concurrent Accordion and Color Transformation Animations

I am currently utilizing jQuery version 2.0.3 and jQuery UI version 1.10.3, specifically using the accordion feature. I am attempting to modify the color of the accordion panels as they open and close by implementing the following code: $(".main-content") ...

The Redux store has been modified, yet the changes are not reflected in the

In my Posts.js component, I am mapping every object in the posts array. Within this function, I attempt to filter all notes that have the same post_id as the id of the current mapped post object and store them in a variable called filteredNotes. I then pas ...

What sets Observables (Rx.js) apart from ES2015 generators?

From what I've gathered, there are various techniques used for solving asynchronous programming workflows: Callbacks (CSP) Promises Newer methods include: Rx.js Observables (or mostjs, bacon.js, xstream etc) ES6 generators Async/Await The trend ...

What is the best way to invoke a function within a controller from a .factory service?

I have been working on a code snippet where I am trying to create a generic function. This function, when given the name of a function in my controller, should be run from a factory. app.factory('myfactory', function () { return { cre ...

"Error: The property $notify is not found in the type" - Unable to utilize an npm package in Vue application

Currently integrating this npm package for notification functionalities in my Vue application. Despite following the setup instructions and adding necessary implementations in the main.ts, encountering an error message when attempting to utilize its featur ...

What is the best way to trigger a jQuery UI dialog using an AJAX request?

My website includes a jQuery UI Dialog that opens a new window when I click the "create new user" button. Is there a way to open this window using an AJAX request? It would be useful if I could open the dialog-form from another page, such as dialog.html ...

The data insertion query in MYSQL seems to be malfunctioning

I am facing an issue with inserting data from a form into a database table named "sumation". Despite using PhpStorm IDE, I am getting errors indicating that no data sources are configured to run the SQL and the SQL dialect is not set up. Can anyone help ...

How can I utilize the JQuery GetJSON function to retrieve HTML content from an external webpage?

Imagine you're attempting a jQuery ajax request like this: $.ajax({ ... url: http://other-website.com ... }) You probably know that due to the same-origin policy, this request will fail because the URL is for an external domain. But the ...

Issue with Internet Explorer: Refusing to run javascript included in AJAX-loaded content

While loading AJAX content that includes a javascript function using the jQuery .load function with done() on completion, I am facing an issue. $('#content').load(a, done); function done() { if(pagejs() == 'function') { ...