How to write JavaScript find and findLast from scratch

Basic implementation of find() & findLast() JS array methods.

·

1 min read

How to write JavaScript find and findLast from scratch

find

Returns the first element that satisfies the testing function otherwise returns undefined.

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


const numbers = [ 1, 2, 3, 4, 5, 6];

const found = numbers._find((num) => num > 4);

console.log(found);

// Output
// 5
  • runs the loop for all elements and if cbFunction returns true then return that element otherwise return undefined.

findLast

Returns first matched value and search starts from last.

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


const numbers = [ 1, 2, 3, 4, 7, 5, 1];

const found = numbers._findLast((num) => num > 4);

console.log(found);

// Output
// 5
  • same as find method but search from last to first.