solution 2 for problem 3 in js