checkIndex function

Check and keep valid index only