2

I have one question. Is there any function in lodash library which is going to provide me the method for comparing each object in both collections by specific property and if the condition is fulfilled then creating another object?

example:

    a) [{a:1,b:'abc',c:'dfr'},{a:3,b:'dfe',c:'gty'}....{}]
    b) [{a:3,b:'fgt',d:'ghr'},{a:5,b:'ghk',d:'bhj'}...{}]

 result:[{a:3,b:'dfe',c:'gty',d:'ghr'}]

I would like to compare these two collections by 'a' parameter and if a parameter is matched then assign parameter 'd' to object from the collection a). I have read something about differenceWith or intersection, but I am not sure if it may work, or maybe there are better functions to do this. Thanks in advance!

aggre1234
  • 73
  • 6

2 Answers2

2

Create a Map of the items in array2 by their keys. Iterate array1 with Array.filter(), and remove all items that their a property is not found in the Map. Use Array.map() to combine the remaining items with d property of their counterpart in the Map:

const array1 = [{a:1,b:'abc',c:'dfr'},{a:3,b:'dfe',c:'gty'}];
const array2 = [{a:3,b:'fgt',d:'ghr'},{a:5,b:'ghk',d:'bhj'}];

// create a Map of array2 items by the a property
const array2Map = new Map(array2.map((o) => [o.a, o]));
const result = array1
  // filter out all items that don't have matching item in the Map
  .filter(o => array2Map.has(o.a))
  // map the items, and add the d property from the item in the Map
  .map(o => ({
    ...o,
    d: array2Map.get(o.a).d
  }));

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

1) Native way: doing array map and comparing inside map loop with assigning objects.

const array1 = [{a:1,b:'abc',c:'dfr'},{a:3,b:'dfe',c:'gty'}];
const array2 = [{a:3,b:'fgt',d:'ghr'},{a:5,b:'ghk',d:'bhj'}];

const result = array1.map(obj1 => {
  const obj2 = array2.find(obj => obj.a === obj1.a);
  if (obj2) return Object.assign({}, obj1, {d: obj2.d});
}).filter(value => value);

console.log(result);

2) Lodash way: same as in example 1 but using only lodash methods

const array1 = [{a:1,b:'abc',c:'dfr'},{a:3,b:'dfe',c:'gty'}];
const array2 = [{a:3,b:'fgt',d:'ghr'},{a:5,b:'ghk',d:'bhj'}];

const result = _.compact(
  _.map(array1, obj1 => {
    const obj2 = _.find(array2, _.matchesProperty('a', obj1.a));
    if (obj2) return _.assign({}, obj1, _.pick(obj2, ['d']));
  })
);

console.log(result);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>


P.S. Try to avoid lodash, underscore and etc stuff as much as possible. JS, ES are rich enough.

num8er
  • 18,604
  • 3
  • 43
  • 57