Home > Net >  Lodash merge two arrays with conditions
Lodash merge two arrays with conditions

Time:10-25

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?

CodePudding user response:

You can use unionBy (lodash)

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

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

CodePudding user response:

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; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related