It’s not clear from your description and screenshot what you want the code to do.
Looks like you are looping over an array of xy positions, and comparing if the cost is greater than the any of the neighbors.
Then it checks if the neighbor isn’t the first index (indexof gives -1 when a value isn’t found) or if the cell is one of the first four in the array.
Other than that keep in mind setting the return value doesn’t exit the function with the event system, so all four events will run if true.
After that I’m not sure what it does. Returns the cost with some location maybe?
What do you want this function to do and how is it not doing it now?