The Mapping Function in Array.from
You'll learn how to transform elements while converting them into an array using Array.from()'s second parameter.
What Is the Mapping Function?
Array.from() accepts an optional second argument: a mapping function. This function is applied to each element during the conversion process, letting you transform values on-the-fly rather than creating the array first and mapping afterward.
Think of it like a factory assembly line: instead of building widgets and then painting them in a separate step, you paint each widget as it comes off the line. It's a single, streamlined operation.
How It Works
The syntax looks like this:
Array.from(arrayLike, mapFn)
The mapping function receives two parameters:
- The current element
- The current index
const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 };
// Transform each element as it's converted
const result = Array.from(arrayLike, (element, index) => {
return element.toUpperCase();
});
console.log(result); // ['A', 'B', 'C']
Why Use It?
This approach is more efficient than chaining operations. Compare:
// Two-step process
const nums = Array.from({ length: 5 }, (_, i) => i);
const doubled = nums.map(n => n * 2);
// Single-step process
const doubled = Array.from({ length: 5 }, (_, i) => i * 2);
console.log(doubled); // [0, 2, 4, 6, 8]
The second version skips creating an intermediate array, doing the transformation immediately.
Key Takeaway: Pass a mapping function as the second argument to Array.from() to transform elements during conversion, combining array creation and transformation into one efficient step.