I am looking for elements in an array with findIndex.
Here is the code:
function findLower(element, index, tarray) {
if (current_value >= element) {
console.log("elected", element)
return index
}
}
const current_value = 15
const ordered_radiuses = [0, 1, 2, 3, 4, 5, 10, 15, 20, 25, 30]
const lower_index = ordered_radiuses.findIndex(findLower)
console.log("lower index", lower_index)
Which prints:
elected 0
elected 1
lower index 1
However, as 0 is lower than 15, and 0 being at index 0, I was expecting the output to be:
elected 0
lower index 0
What am I understanding wrong here ?
See the docs:
callbackFn
A function to execute on each value in the array until the function returns true, indicating that the satisfying element was found.
You are returning index and not a boolean.
0 is a false value.
1 is a true value.
Replace return index with return true or, if you don't need the logging, replace the whole if statement with return current_value >= element
It's almost fine, but you're returning the index and it's 0 on the first loop. And as 0 is handled as false it's going to the second value of your array. So that's how it must look like:
function findLower(element, index, tarray) {
if (current_value >= element) {
console.log("elected", element);
return true;
}
}
const current_value = 15;
const ordered_radiuses = [0, 1, 2, 3, 4, 5, 10, 15, 20, 25, 30];
const lower_index = ordered_radiuses.findIndex(findLower);
console.log("lower index", lower_index);
You should pass a predicate to findIndex and should return either true or false and you are returning the index which would produce the unexpected result
function findLower(element, index, tarray) {
return current_value >= element;
}
const current_value = 15;
const ordered_radiuses = [0, 1, 2, 3, 4, 5, 10, 15, 20, 25, 30];
const lower_index = ordered_radiuses.findIndex(findLower);
console.log("lower index", lower_index);