Home > Software engineering >  Merge two arrays with shared value
Merge two arrays with shared value

Time:09-16

I have two arrays of objects:

let employees = [
  { name: 'Jason', job_id: '101' },
  { name: 'Sarah', job_id: '102' },
  { name: 'Jack', job_id: '102' }
]

let jobs = [
  { job_id: '101', position: 'Designer' },
  { job_id: '102', position: 'Developer' }
]

Is it possible for me to merge these arrays into one with vanilla javascript, like below:

let employees = [
  { name: 'Jason', job_id: [job_id: '101', position: 'Designer'] },
  { name: 'Sarah', job_id: [job_id: '102', position: 'Developer'] },
  { name: 'Jack', job_id: [job_id: '102', position: 'Developer'] }
]

Below is what I have now. It does give me the correct result, however if possible I'd rather not use nested loops.

employees.forEach(employee => {
  for (let index = 0; index < jobs.length; index  ) {
    if (employee.job_id == jobs[index].job_id) {
      employee.job_id= jobs[index];
    }
  }
})

CodePudding user response:

The task is not very complicated so i will try to make a simple answer with a live demo.

The idea here is to loop through the employees array and then construct an object having the structure you want and then push it into a final array.

Each object on the final array will have the following attributes:

  • name: equal to the name on the employees array (on every iteration)
  • job: to make things clearer, i'd use job instead of job_id (which you use in your desired result). The job is an object containing
    • id: the job_id from the employees array
    • position: the respective position from the jobs array.

To have the above result, we will use the reduce method wich will construct the final array along the way.

The other task is to get the respective position, from the jobs array, based on the job_id from the employees table. To do so, we'll use the find method wich will return the first match it finds on the jobs array.

With that being said, let's have a live demo (the demo has some useful comments):

const employees = [{
      name: 'Jason',
      job_id: '101'
    },
    {
      name: 'Sarah',
      job_id: '102'
    },
    {
      name: 'Jack',
      job_id: '102'
    }
  ],
  jobs = [{
      job_id: '101',
      position: 'Designer'
    },
    {
      job_id: '102',
      position: 'Developer'
    }
  ],
  /** 
   * "res" is the resulting array after performing the needed operations 
   * "reduce" method loops through the "employees" array and populates the "res" array along the way
   */
  res = employees.reduce((a, c) => {
    /**
     * a: the accumulator, it holds the last value from the previous iteration. Initially it equals to an empty array "[]" (see 3rd argument passed to the "reduce" method)
     * c: is the current element from the "employees" array on each iteration
     */

    /** adds an object that follows the intended structure to the final array */
    a.push({
      name: c.name,
      job: {
        id: c.job_id,
        /** 
         * find the respective "position" based on the "job_id" of the current element of element of the "employees" arrray 
         * el: holds the element from "jobs" array on each iteration of the "find" method
         * the condition is once we find an elemnt having "job_id" equals to the current element (i mean "c" parameter) "job_id" then return that object's "position" attribute
         * once we found the "position" we simply save it on the object we're constructing
         */
        position: jobs.find(el => el.job_id == c.job_id).position
      }
    });
    /** return the array so that the next iteration of "reduce" can do its work */
    return a;
  }, []);

/** print the result */
console.log(res);

The above demo is definitely not the only way to have things done, surely there are some fancy ES6 ways to do that especially when it comes to constructing the objects. For the sake of simplicity, i wouldn't use those fancy/complicated tricks to keep things as simple and understandable as possible.

Learn more about the reduce method on MDN.

Learn more about the find method on MDN.

  • Related