← All examples

Count occurrences

TypeScript Loops

loop + counter

Flowchart (ISO 5807)

YesNoStartInput a, keycount = 0i = 0, a.length - 1, 1a[i] === keycount++Return countEndFigure 1 — countOccurrences

Source code

function countOccurrences(a: number[], key: number): number {
    let count = 0;
    for (let i = 0; i < a.length; i++) {
        if (a[i] === key) {
            count++;
        }
    }
    return count;
}