Jacob's special treatment of Joseph, together with the dreams he recounted, not only engendered feelings of jealousy and animosity but were interpreted by his brothers as an attempt to usurp leadership from the firstborn. They believed it was necessary to eliminate the threat he posed to protect the fledgling Israelite nation.
Reuben convinced the other brothers to leave Joseph to die in a pit rather than killing him themselves. His intention was to rescue Joseph at a later time. Yet after Reuben departed, Judah persuaded the other brothers that they should sell Joseph into slavery rather than leave him to die alone.
It seems that Judah's motive was admirable; he offered the brothers a compromise by both sparing Joseph's life while eliminating the threat they thought Joseph posed to their family. The Midrash, however, asserts that sale of Joseph was indeed a grave sin (Mishlei 1).
Nevertheless, despite instigating this terrible misdeed, Judah was considered worthy enough for the future Jewish monarchic line to come exclusively from his descendants. Jacob blesses Judah, saying: "The staff shall not depart from Judah, nor the sceptre from between his feet" (Genesis 49:10). How did Judah merit such greatness given what he had done to Joseph?
Rabbi Avigdor Neventzal, rabbi of the Old City of Jerusalem, explains the connection. When Joseph finally tested his brothers by planting his silver goblet in Benjamin's sack and seizing Benjamin as his slave, it was Judah who came forward to offer himself in Benjamin's place. Judah's selfless act, effectively selling himself into slavery for Joseph's younger brother rectified his original wrongdoing and implanted into his progeny the fundamental trait of shouldering responsibility, vital for the future Jewish monarchy.