use reduce function instead of forEach.

also removed the events global variable.