Function replace

  • Category

    Replace the first occurrence 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 index of the replaced element, or -1 if it is not present.

    Array

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

    replace(array, 1, 2);

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