javascript / beginner
Snippet
Transforming Number Values with Array Map and Derived Data
Array.prototype.map iterates through each numerical value of an array and creates a new array of objects containing computed values. In this example, each raw price is transformed into formatted string representations of net and gross amounts, demonstrating functional immutable data transformation.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script>let rawPrices = [15.00, 42.50, 99.99];const VAT_RATE = 1.19;$: priceBreakdowns = rawPrices.map(price => ({net: price.toFixed(2),gross: (price * VAT_RATE).toFixed(2)}));</script><ul>{#each priceBreakdowns as item}<li>Net: ${item.net} — Gross (incl. tax): ${item.gross}</li>{/each}</ul>
svelte
Breakdown
1
let rawPrices = [15.00, 42.50, 99.99];
Defines an array containing base numeric floating-point values.
2
$: priceBreakdowns = rawPrices.map(price => ({ ... }));
Applies Array.map reactively to transform every number into a structured object.
3
(price * VAT_RATE).toFixed(2)
Calculates the tax-included number and formats it to a fixed two-decimal string.