Javascript solution for problem 2.