Thank you again for the additional explanations.
At the moment my problem is solved.
I will make a note to try out your suggested algorithm to see if it makes an improvement over the solution I chose for now.
I have a lot more to learn about javascript and your explanations helped me a lot to that end.