How to break out of multiple for loops at once in JavaScript

2 Answers

0 votes
/// Searches a 2D matrix and breaks out of both loops immediately using a labeled break.
function searchMatrixLabeled(matrix, target) {
    let coordinates = null;

    // Assign a label to the outer loop
    outerLoop: for (let i = 0; i < matrix.length; i++) {
        for (let j = 0; j < matrix[i].length; j++) {
            if (matrix[i][j] === target) {
                coordinates = { row: i, col: j };
                // Break out of the outer loop (which terminates both loops instantly)
                break outerLoop;
            }
        }
    }

    return coordinates;
}

function main() {
    const matrix = [
        [10, 20, 30],
        [40, 50, 60],
        [70, 80, 90]
    ];

    const target = 50;
    const result = searchMatrixLabeled(matrix, target);

    if (result) {
        console.log(`[Labeled Break] Found target at row ${result.row}, col ${result.col}`);
    } else {
        console.log("[Labeled Break] Target not found.");
    }
}

main();


/*
run:

[Labeled Break] Found target at row 1, col 1

*/

 



answered 1 day ago by avibootz
edited 1 day ago by avibootz
0 votes
/// Searches a 2D matrix using short-circuiting array methods (`some`).
function searchMatrixFunctional(matrix, target) {
    let coordinates = null;

    // .some() stops execution as soon as any row returns true
    matrix.some((row, i) => {
        return row.some((value, j) => {
            if (value === target) {
                coordinates = { row: i, col: j };
                return true; // Signals row.some to stop
            }
            return false;
        });
    });

    return coordinates;
}

function mainAlternative() {
    const matrix = [
        [5, 12, 19],
        [22, 35, 41],
        [50, 68, 74]
    ];

    const target = 35;
    const result = searchMatrixFunctional(matrix, target);

    if (result) {
        console.log(`[Functional Approach] Found target at row ${result.row}, col ${result.col}`);
    } else {
        console.log("[Functional Approach] Target not found.");
    }
}

mainAlternative();


/*
run:

[Functional Approach] Found target at row 1, col 1

*/

 



answered 1 day ago by avibootz
edited 1 day ago by avibootz
...