Array.find weird result
-
I'm trying to get my head around the find function but in this example I get a wrong result for
sample == 0
(or negative values). But it works for other positive values...inline function searchInArray(sample) { Console.print("> sample -> " + sample); local myArray = [0, 5, 10, 15, 20]; local element = myArray.find(function[sample](currentValue, index, arr) { Console.print("Value tested: " + currentValue + " | Is sample lower or equal? " + ((sample <= currentValue) ? ">TRUE" : "!FALSE")); if (sample <= currentValue) return currentValue; }, myArray); Console.print("> Element returned -> " + element); // spits the second element instead of first } searchInArray(0);
-
@ustk Why not just use indexOf in this case? find is more useful when the array contains objects.
-
@d-healey I'm looking for the case where
sample
is between two values in the array and report the one just below.
Of course, I could just use a loop iterator in this example, but I'd like to master those find/map/some functions... -
Yeah I'd just use a loop. I'm not sure why
find
is not doing what's expected though... Also you don't need to set the second parameter asmyArray
because that's already there in the third parameter of the test function.This is what I would do
local myArray = [0, 5, 10, 15, 20]; local element; for (x in myArray) { if (sample <= x) { element = x; break; } }