Two Pointer Algorithm Javascript Foreach Loop