Home > Software design >  How can I find last index in array with method findIndex() in proper interval? JS
How can I find last index in array with method findIndex() in proper interval? JS

Time:03-26

The function using FindIndex should find the latest index of an array of A6, the value of which lies from A6_FROM to A6_TO (more A6_FROM but less A6_TO). Display the found index in OUT-6. If the value is not found, to output FALSE.

let a6 = [13, 15, 22, 23, 26, 35, 72];
let a6_from = 23;
let a6_to = 67;
const f6 = () => {
  let res = a6.findIndex((item) => {
    return item > a6_from && item < a6_to;
  });
  document.querySelector('.out-6').innerHTML = `${res}`;
}

CodePudding user response:

If you find the latest index of array you can use

const x = a6[a6.length-1]

x will be a6's last item.

const f6 = () => {
    a6.findIndex(item => {
       return item === x
    })
}

and if you wanna find index with x you can use this way.

CodePudding user response:

This does not use findIndex at all.

It creates an array of objects to store the value and index of the a6 array. It filters that array so each value is between a6_from and a6_to. Then it takes the index property of the final element.

let a6 = [13, 15, 22, 23, 26, 35, 72];
let a6_from = 23;
let a6_to = 67;

const meetsCondition = a6.map((value, index) => ({value, index})).filter(e => e.value > a6_from && e.value < a6_to);
const res = meetsCondition[meetsCondition.length - 1].index;

console.log(res);

CodePudding user response:

You can use map() to produce [index, element] pairs, then use filter() to obtain only those pairs where the element satisfies the condition.

Prepend the resulting array with [-1,0] or some other way to indicate that no element was found. Then use .pop()[0] to get the desired index. -1 would indicate no such element was found.

const a6 = [13, 15, 22, 23, 26, 35, 72];
const a6_from = 23;
const a6_to = 67;

const a6_out = [[-1,0]].concat(
    a6.map((e,i) => [i, e]).filter(([i,e]) => e > a6_from && e < a6_to)
).pop()[0];
//returns -1 if not found
console.log( a6_out );

  • Related