Hone logo
Hone
Problems

Filling an Array with a Specific Value in JavaScript

This challenge focuses on efficiently populating a JavaScript array with a given value. This is a common task in programming, useful for initializing data structures, creating arrays of a specific size, or resetting array contents. Your goal is to write a function that takes an array and a value as input and modifies the array so that all its elements are equal to the specified value.

Problem Description

You are tasked with creating a JavaScript function called fillArray that takes two arguments:

  • arr: An array of any data type.
  • value: The value to fill the array with.

The function should modify the original arr in-place, replacing each element with the value. The function should not return anything (void).

Key Requirements:

  • The function must modify the original array directly. Do not create a new array.
  • The function should work correctly for arrays of any length, including empty arrays.
  • The function should work correctly with arrays containing any data type (numbers, strings, booleans, objects, etc.).

Expected Behavior:

After calling fillArray(arr, value), the arr variable should be updated such that all its elements are equal to value.

Edge Cases to Consider:

  • Empty Array: The function should handle an empty array gracefully without errors.
  • Array with Mixed Data Types: The function should correctly fill the array regardless of the existing data types.
  • Null or Undefined Input: While not strictly required, consider how your function should behave if arr is null or undefined. (Throwing an error is acceptable).

Examples

Example 1:

Input: [1, 2, 3, 4, 5]
Output: [5, 5, 5, 5, 5]
Explanation: The array [1, 2, 3, 4, 5] is filled with the value 5, resulting in [5, 5, 5, 5, 5].

Example 2:

Input: ["a", "b", "c"]
Output: ["x", "x", "x"]
Explanation: The array ["a", "b", "c"] is filled with the value "x", resulting in ["x", "x", "x"].

Example 3:

Input: []
Output: []
Explanation: An empty array remains empty after being filled with any value.

Constraints

  • The input array arr can contain any number of elements (including zero).
  • The value can be of any JavaScript data type.
  • The function must operate in O(n) time complexity, where n is the length of the array. This means you should iterate through the array once.
  • The function must modify the array in-place. Creating a new array is not allowed.

Notes

Consider using a for loop or other iteration methods to efficiently traverse the array and update its elements. Think about how to handle potential errors if the input array is invalid (e.g., null or undefined). The goal is to write clean, efficient, and robust code.

Loading editor...
javascript