How to write JavaScript findIndex and findLastIndex from scratch

·

1 min read

How to write JavaScript findIndex and findLastIndex from scratch

findIndex

Returns the index of the element that returns true on a callback function.

Array.prototype._findIndex = function(cbFunction) {
    for(let i = 0; i < this.length; i++) {
        if(cbFunction(this[i], i, this)) {
            return i
        }
    }

    return -1
}

const numbers = [5, 10, 15, 20, 25];

console.log(numbers._findIndex((num) => num > 10));
// Output
// 2
  • loop array then if cbFunction returns true and then returns the index of that element.

  • otherwise, return -1.

findLastIndex

Returns index of an element that returns true on callback function in a reverse array.

Array.prototype._findLastIndex = function(cbFunction) {
    for(let i = this.length - 1; i >= 0; i--) {
        if(cbFunction(this[i], i, this)) {
            return i
        }
    }

    return -1
}

const numbers = [5, 10, 15, 20, 25];

console.log(numbers._findLastIndex((num) => num < 25));
// Output
// 3