How to orient a part so that two of its axises match another part, but the third axis is exactly the same?

Very confusing title, I know! But here are the details:
I’m working on something and I need to basically orient a part so there’s a only one axis difference. Still sounds confusing, but look at the images below:

This is what I would maybe have:


And this is what I’d like to happen:
image
On the first image, none of the rotation axises is lined up with the other part, but on the second image you can see that only the Z axis is different, the other axises are lined up.
Note that specifically, I’m looking to rotate the two axies with the smallest differences (notice how it was the axis with the biggest difference that I left untouched in the example above?) and it should be rotated to the “closest axis point”.
What I mean is:
image
Here (the image above) we have two parts, but this time I marked the top-surfaces with studs (to showcase what I mean easier). Now, instead of the part rotating so it matches the other part completely, it rotates to the nearest axis point so its still aligned, but not necessarilly pointing in the same direction:
image

That is the desired behaviour I want (and am trying to achieve).
Last thing to note is that the block I’m always comparing to, can be at any orientation (not just 0,0,0) so it’s important for it to work at any orientation.
If you need any more information (or are confused about a part) feel free to ask for more information and I’ll respond back.

partA.Orientation = Vector3.new(partB.Orientation.X, partB.Orientation.Y, partA.Orientation.Z)

‘partA’ gets the ‘X’ and ‘Y’ axis orientations from ‘partB’ but preserves its current ‘Z’ axis orientation.