The array
argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses filter()
to extract the positive values and then uses findIndex()
to find the first element that is less than its neighbors.
const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6];
const firstTrough = numbers
.filter((num) => num > 0)
.findIndex((num, idx, arr) => {
// Without the arr argument, there's no way to easily access the
// intermediate array without saving it to a variable.
if (idx > 0 && num >= arr[idx - 1]) return false;
if (idx < arr.length - 1 && num >= arr[idx + 1]) return false;
return true;
});
console.log(firstTrough); // 1