Clay Banks
Clay Banks

Reputation: 4581

Join Two Arrays on a Matching Object Property

I have two arrays that I would like to join

const users = [{ user_id: 100, name: 'Bob' }, { user_id: 101, name: 'Joe' }]

const departments [{ id: 900, manager: 100 }, { id: 901, manager: 101 }]

I want to create a new departments array that contains the user's name by matching the user_id property to the department's manager property.

Is there a simple way to achieve this in lodash (or plain Javascript) ?

The new array would look like this

[{ id: 900, manager: 100, name: 'Bob' }, { id: 900, manager: 101, name: 'Joe' }];

Any help is appreciated!

Upvotes: 1

Views: 242

Answers (2)

trincot
trincot

Reputation: 350300

You can use a Map for faster lookup, and then make the mapping:

const users = [{ user_id: 100, name: 'Bob' }, { user_id: 101, name: 'Joe' }],
    departments = [{ id: 900, manager: 100 }, { id: 901, manager: 101 }];

const names = new Map(users.map( user => [user.user_id, user.name] )),
    res = departments.map( dep => Object.assign({ name: names.get(dep.manager) }, dep) );

console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Note that the extra step of creating a Map will lead to O(n) time efficiency as opposed to O(n²) when using an array searching method in each iteration. This is not relevant for small user arrays, but will be when working with larger array sizes.

Upvotes: 8

mdatsev
mdatsev

Reputation: 3879

You can easily do it with just JavaScript using map and find:

const users = [{ user_id: 100, name: 'Bob' }, { user_id: 101, name: 'Joe' }]
const departments = [{ id: 900, manager: 100 }, { id: 901, manager: 101 }]

const result = departments
  .map(d => ({
    ...d,
    name: users.find(u =>
      u.user_id === d.manager).name
  }));

console.log(result);

Upvotes: 4

Related Questions