Transform Each Item in an Array in JavaScript
Transforming every item in an array is one of the most practical and satisfying operations in JavaScript. Whether you’re capitalizing fruit names, doubling numbers, or reformatting data into custom messages, this pattern is essential to becoming fluent in array manipulation.
The idea is simple: take each element from an array, apply a transformation (such as modifying, replacing, or reformatting), and return a new array with those updated values. JavaScript provides elegant ways to do this using built-in functions like map()
and forEach()
, as well as the classic for
loop.
Method 1: Using map()
for Clean Transformation
The map()
method is the most expressive and widely used way to transform arrays. It creates a brand-new array, where each item is the result of a transformation you define. This is perfect for beginners and professionals alike who want readable, modern code.
const fruits = ["apple", "banana", "cherry"];
const uppercaseFruits = fruits.map(fruit => {
return fruit.toUpperCase();
});
console.log("Original:", fruits);
console.log("Transformed:", uppercaseFruits);
Original: [ 'apple', 'banana', 'cherry' ]
Transformed: [ 'APPLE', 'BANANA', 'CHERRY' ]
Method 2: Using forEach()
with Manual Collection
While forEach()
is not meant to return a new array directly, you can still use it to build a transformed version manually. This is useful when you want to mutate or collect new data but don’t need the functional style of map()
.
const items = ["Item 1", "Item 2", "Item 3"];
const labeledItems = [];
items.forEach((item, index) => {
labeledItems.push("Label " + (index + 1) + ": " + item);
});
console.log("Original:", items);
console.log("Transformed:", labeledItems);
Original: [ 'Item 1', 'Item 2', 'Item 3' ]
Transformed: [ 'Label 1: Item 1', 'Label 2: Item 2', 'Label 3: Item 3' ]
Method 3: Using a for
Loop for Full Control
When you want absolute control over how elements are processed—perhaps with conditional logic or nested transformation—a classic for
loop is your best bet. It’s verbose, yes, but also crystal-clear for educational purposes.
const numbers = [1, 2, 3, 4];
const doubled = [];
for (let i = 0; i < numbers.length; i++) {
doubled.push(numbers[i] * 2);
}
console.log("Original:", numbers);
console.log("Transformed:", doubled);
Original: [ 1, 2, 3, 4 ]
Transformed: [ 2, 4, 6, 8 ]
When Should You Use Each Method?
Use map()
when you want a clean, expressive, and reusable way to generate a new array from an existing one. Choose forEach()
when you're applying side-effects or building new arrays step by step. And go with the for
loop when you need precise control, especially if transformation requires more logic than just one line.
Comments
Loading comments...