Merging simple values

Let's merge some simple list values using the merge() method:

const myList1 = List.of(1, 2, 3);
const myList2 = List.of(2, 3, 4, 5);
const myMergedList = myList1.merge(myList2);

console.log('myList1', myList1.toJS());
// -> myList1 [ 1, 2, 3 ]
console.log('myList2', myList2.toJS());
// -> myList2 [ 2, 3, 4, 5 ]
console.log('myMergedList', myMergedList.toJS());
// -> myMergedList [ 2, 3, 4, 5 ]

When we merge myList1 and myList2, we have a conflict in index positions 0, 1, and 2. This is why the values 2, 3, and 4 are in myMergedList. The final value, 5, doesn't conflict with anything in myList1, so it will always end up in the merged result.

Once again, you might want to preserve the original values when there's a conflict. For this, you'll use the mergeWith() method again:

const myMergedWithList = myList1.mergeWith(
(a, b) => a === undefined ? b : a,
myList2
);

console.log('myMergedWithList', myMergedWithList.toJS());
// -> myMergedWithList [ 1, 2, 3, 5 ]

Unlike map merges, you actually need both of the mergeWith() iteratee arguments. You have to check to see if the first value, a, is undefined. This means that there's no index for the value in b, in which case we just want to return b. For example, the value 5 in myList2 is at index 4. There's no index 4 value in myList1; so, this is how you add it to the merged result.

Let's try reversing the order of the two lists using our mergeWith() approach and see what happens:

const myMergedReversed = myList2.mergeWith(
(a, b) => a === undefined ? b : a,
myList1
);

console.log('myMergedReversed', myMergedReversed.toJS());
// -> myMergedReversed [ 2, 3, 4, 5 ]

This time, we're taking myList2 and merging myList1 into it. Every value in myList1 has a conflict in myList2, so nothing from myList1 is merged into myMergedReveresed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.229.113