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

174
Views
Lodash merge two arrays with conditions

I have 2 arrays like below:

const array1 = [{name: "1"}, {name: "2"}, {name: "3"}, {name: "4"}, {name: "4"}];
const array2 = [{name: "1"}, {name: "5"}, {name: "3"}, {name: "4"}, {name: "4"}, {name: "4"}, {name: "1"}, {name: "1"}, {name: "2"}];

Expected Output is:

[{name: "1"}, {name: "2"}, {name: "3"}, {name: "4"}, {name: "4"}, {name: "5"}, {name: "4"}, {name: "1"}, {name: "1"}];

The result array should contain the array1's all elements and those elements from array2 that are not already present in array1

I tried using _.unionBy

_.unionBy(array1, array2, 'name')

but it only results an array with uniq 'name'

How can we achieve that using lodash?

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

0

You can use unionBy (lodash)

let result = _.unionBy(array1 , array2, 'name');

unionBy - https://docs-lodash.com/v4/union-by/

about 4 years ago · Juan Pablo Isaza Report

0

Assuming you do not want { name: "2" } as last item of the result set, you could count the grouped items and add wanted items.

const
    array1 = [{ name: "1" }, { name: "2" }, { name: "3" }, { name: "4" }, { name: "4" }],
    array2 = [{ name: "1" }, { name: "5" }, { name: "3" }, { name: "4" }, { name: "4"}, { name: "4" }, { name: "1" }, { name: "1" }, { name: "2" }],
    counts = {},
    result = array1.map(o => (counts[o.name] = (counts[o.name] || 0) + 1, o));

result.push(...array2.filter(o => !counts[o.name] || !counts[o.name]--));

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

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!