Array Replace

Description


Given an array of integers, replace all the occurrences of elemToReplace with substitutionElem.

Example

For inputArray = [1, 2, 1], elemToReplace = 1, and substitutionElem = 3, the output should be arrayReplace(inputArray, elemToReplace, substitutionElem) = [3, 2, 3].

Input/Output

  • [execution time limit] 4 seconds (js)

  • [input] array.integer inputArray

    A positive integer.

    Guaranteed constraints:
    0 \leq inputArray.length \leq 10^4,
    0 \leq inputArray[i] \leq 10^9.

  • [input] integer elemToReplace

    Guaranteed constraints:
    0 \leq elemToReplace \leq 10^9.

  • [input] integer substitutionElem

    Guaranteed constraints:
    0 \leq substitutionElem \leq 10^9.

  • [output] array.integer

[JavaScript (ES6)] Syntax Tips

1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
console.log("This prints to the console when you Run Tests");
return "Hello, " + name;
}

Solution


1
2
3
function arrayReplace(inputArray, elemToReplace, substitutionElem) {
  return inputArray.map(el => (el === elemToReplace ? substitutionElem : el));
}