Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
How to join 2 array object using lodash

I want to join a with b using lodash here is my data

const a = 
  [ { id: 1, job: 'engineer' } 
  , { id: 2, job: 'police'   } 
  , { id: 3, job: 'thief'    } 
  ] 
const b = 
  [ { name: 'test1', score: 1, aId: [ 1, 2 ] } 
  , { name: 'test2', score: 3, aId: [ 1, 3 ] } 
  ] 

Here is my output that I want

const result = 
  [ { id: 1, job: 'engineer', score: [ {name: 'test1'}, {name: 'test2'} ] } 
  , { id: 2, job: 'police',   score: []                                   } 
  , { id: 3, job: 'thief',    score: [ {name: 'test 3'} ]                 } 
  ] 

this is what I try I'm using 2 map data and inside the second map I use include check between 2 arrays..

_.map(a, function(data:any) {
    const name = _.map(b, function(dataB:any) {
        // in here I check
        const isValid = dataB.aId.includes(a.id)
        if(isValid){
            return {
                name = dataB.name
            }
        }
    })
    return {
        id: data.id
        job: data.job
        score: name
    }
});

this method also work but is their any better method than using 2 map ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Reduce b to a map of id to array of tests, and then map a, and take the relevant array from the map to create each object:

const a = 
  [ { id: 1, job: 'engineer' } 
  , { id: 2, job: 'police'   } 
  , { id: 3, job: 'thief'    } 
  ] 
const b = 
  [ { name: 'test1', score: 1, aId: [ 1, 2 ] } 
  , { name: 'test2', score: 3, aId: [ 1, 3 ] } 
  ] 
  
const bMap = b.reduce((acc, { name, aId }) => {
  const nameObject = { name }
  
  aId.forEach(id => {
    if(!acc.has(id)) acc.set(id, [])
    
    acc.get(id).push(nameObject)
  })

  return acc
}, new Map())

const result = a.map(o => ({ ...o, scores: bMap.get(o.id) }))

console.log(result)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!