changed logic  with help of Array.prototyp.reduce