Hone logo
Hone
Problems

JavaScript Array Cloning Challenge

Arrays are fundamental data structures in JavaScript. Often, you'll need to create an independent copy of an array to avoid unintended modifications to the original. This challenge focuses on implementing robust methods for cloning arrays in JavaScript.

Problem Description

Your task is to create a function that takes an array as input and returns a new array that is a shallow copy of the original. A shallow copy means that the new array contains the same elements as the original, but if those elements are themselves objects or arrays, only references to those original objects/arrays are copied, not the objects/arrays themselves.

Requirements:

  1. Create a function: Name your function cloneArray.
  2. Input: The function should accept a single argument, which is an array.
  3. Output: The function must return a new array that is a shallow copy of the input array.
  4. Immutability: The original array should not be modified by the cloning process.
  5. Shallow Copy: For elements that are primitive types (numbers, strings, booleans, null, undefined, symbols, bigints), their values should be copied. For elements that are objects or arrays, references to the original objects/arrays should be copied.

Edge Cases to Consider:

  • Empty arrays.
  • Arrays containing various data types (primitives, objects, null, undefined).

Examples

Example 1:

Input: [1, 2, 3, 4, 5]
Output: [1, 2, 3, 4, 5]
Explanation: A simple array of numbers is copied. The new array has the same values.

Example 2:

Input: ["apple", "banana", "cherry"]
Output: ["apple", "banana", "cherry"]
Explanation: An array of strings is copied.

Example 3:

Input: [1, { name: "Alice" }, [7, 8]]
Output: [1, { name: "Alice" }, [7, 8]]
Explanation: The array contains a number, an object, and another array. The cloned array contains the same number and references to the original object and array. Modifying the object or array inside the cloned array will affect the original, and vice-versa.

Example 4:

Input: []
Output: []
Explanation: An empty array should be cloned into a new empty array.

Constraints

  • The input will always be a valid JavaScript array.
  • The array can contain any valid JavaScript data types, including primitives, objects, and other arrays.
  • Your solution should be efficient and handle arrays of reasonable size without performance issues.

Notes

There are several built-in JavaScript methods and syntax that can be used to achieve array cloning. Consider exploring methods like slice(), the spread syntax (...), and Array.from(). Think about which methods are most appropriate for creating a shallow copy. Remember that deep cloning, where nested objects/arrays are also copied, is not the goal here.

Loading editor...
javascript