How can you use .indexOf to locate the index of an array where the numbers stop increasing?
I'm taking in an array and need to return the index value where the numbers start to increase or decrease. The numbers in the array either increase then decrease [1, 3, 6, 4, 3](output = 2) decrease then increase [6, 4, 10, 12, 19](output = 1) or the same sequence [1, 3, 5, 7, 9](output = -1). For now I'm just focused on returning the index of an array that increase then decrease, then I think I can figure the other conditions out.
function ArrayChallenge(arr){
for(let i = 0; i < arr.length; i++){
if(arr[i]>arr[i+1]){
console.log(arr.indexOf(arr[i]>arr[i+1]))
}
}
}
console.log(ArrayChallenge([1, 2, 4, 5, 7, 3]))
To me the code says, take in the argument for the parameter(arr
), then the for loop will go through each index and compare i
with i+1
, if i
is greater than i+1
that means the sequence is decreasing. If that's the case I'd like to console log the index where that's actually happening. For my example code above the output should be 5 because that's the index where the numbers start decreasing, but I'm getting -1 which means the element cannot be found. If someone knows where I'm going wrong and can point me in the right direction that would be great, I'm pretty sure I'm using the .indexOf
method incorrectly, but I don't know why.
"arr[i]>arr[i+1]" returns a bool "true". Your array does not contain any bool values so there is no matching index for it. Therefore it returns -1 because it can not find any matching element.
EDIT:
If you want to print out the "moment" when your values are decreasing you can try something like this:
console.log('Decreasing from index: ' + arr.indexOf(arr[i]) + ' to ' + arr.indexOf(arr[i + 1]))