The total momentum of the system (cart 1+ cart 2) is conserved after the collision.
The initial momentum is

(1)
where the negative sign in front of cart 2 momentum is due to the fact it goes in the opposite direction of cart 1.
The final momentum is

(2)
because the two carts stick together, therefore their total mass is (m1+m2) moving at the new speed vf.
By requiring that (1) is equal to (2), we can solve to find the final speed vf:


where the positive sign means the two carts are now going in the positive direction (i.e. the initial direction of cart 1)