Given the following code,
const arr = [0, 2, 6, 10, 14, 18, 22];
const number = 13;
let index;
I would like to find the index of number
where the following condition apply.
number
>= to the array element but smaller than the next element.
For example here index
would be 3 as arr[3]
is bigger than 10 but smaller than 14
I am unsure if there is an array method to find that solution.
Any help I’d appreciate.
CodePudding user response:
You can use findIndex
const arr = [0, 2, 6, 10, 14, 18, 22];
const number = 13;
let index = arr.findIndex((element, index) => number >= element && number < arr[index 1])
console.log(index)
CodePudding user response:
const arr = [0, 2, 6, 10, 14, 18, 22];
const number = 13;
let index;
for (let i = 1; i < arr.length; i ) {
const prevNum = arr[i - 1]
const currNum = arr[i];
if (prevNum <= number && currNum > number) {
index = i - 1;
}
}
console.log(index)