Finding the index for which a certain of element of an array exists in another array for last time

Viewed 61
arr = ['1', '2', '3', '4', '+', '-', '*', '5', '6']
operatorsValue = ['+', '-', '*', '/', '%']
operatorPosition = arr.findIndex((x) => operatorsValue.includes(x));

Using operatorPosition I can find the index of '+' but i want to find the operator of '*' in the arr.

3 Answers

There's no built-in findLastIndex method on arrays. Just loop backward through the array looking for a match:

let operatorPosition;
for (let i = arr.length - 1; i >= 0; --i) {
    if (operatorsValue.includes(arr[i])) {
        operatorPosition = i;
        break;
    }
}

You can use array#reduce and array#indexOf to create an object with the indexes of all the operators in the array.

let oprObject = operatorsValue.reduce((acc, opr) => {
  acc[opr] = arr.indexOf(opr)
  return acc
}, {})

Demo:

arr = ['1', '2', '3', '4', '+', '-', '*', '5', '6']
operatorsValue = ['+', '-', '*', '/', '%']

let oprObject = operatorsValue.reduce((acc, opr) => {
  acc[opr] = arr.indexOf(opr)
  return acc
}, {})

console.log(oprObject)
console.log("+ is at index:", oprObject["+"])
console.log("* is at index:", oprObject["*"]) 

Compute the last index for each operator and take the max of them:

arr = ['1', '2', '3', '4', '+', '-', '*', '5', '6']
operatorsValue = ['+', '-', '*', '/', '%']
lastOperatorPosition = Math.max(...operatorsValue.map(op => arr.lastIndexOf(op)))

console.log(lastOperatorPosition)

Related