Function replaceAll

  • Category

    Replace all occurrences of searchElement with replacement in an array. Strict equality (===) is used to compare elements.

    Time complexity: O(n)

    Space complexity: O(1)

    Type Parameters

    • T

    Parameters

    • array: T[]

      The array to replace elements in

    • searchElement: T

      The element to search for

    • replacement: T

      The element to replace searchElement with

    Returns number

    The number of elements replaced

    Array

    Example

    const array = [1, 2, 1, 3, 1];

    replaceAll(array, 1, 2);

    console.log(array); // [2, 2, 2, 3, 2]