The easiest way to do this is with
lerp(). For example:
velocity.x = lerp(velocity.x, 0, friction)
friction is some value between
1. This will cause the player's horizontal speed to gradually ramp down to 0 from its current value.
You can see this in practice with a full explanation here: