← All examples

Linear search

JavaScript Algorithms

loop + return index

Flowchart (ISO 5807)

YesNoStartInput arr, keyi = 0, arr.length - 1, 1arr[i] === keyReturn iEndReturn -1EndFigure 1 — indexOf

Source code

function indexOf(arr, key) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === key) {
            return i;
        }
    }
    return -1;
}