Creating a New Array from an Existing Array using JavaScript
Overview
Creating a new array from an existing one is a common task in JavaScript, often required for filtering, transforming, or copying data. This snippet demonstrates an efficient way to create a new array based on the elements of an existing array.
Code
New Array Creation Function
function createNewArrayFromArray(originalArray, transformFunction) {
return originalArray.map(transformFunction);
}
Example Usage
Creating a New Array with Squared Values
const originalArray = [1, 2, 3, 4, 5];
const squaredArray = createNewArrayFromArray(originalArray, (num) => num * num);
console.log("Squared Array:", squaredArray); // Output: [1, 4, 9, 16, 25]
Code Description
The createNewArrayFromArray
function is a versatile utility for array manipulation:
- Purpose: To create a new array by applying a transformation function to each element of an existing array.
- Implementation: Uses the
map
method of the Array object, which creates a new array populated with the results of calling the provided function on every element in the calling array. - Parameters:
originalArray
: The array to be transformed.transformFunction
: A function that is called on each element of the original array.
- Return Value: A new array containing the transformed elements.
This function is highly useful for data processing tasks, where modification or computation based on array elements is required.