blokboard/ Open app

EXAMPLE 05 OF 16 · Starter

Calculate order totals with JavaScript

Turn a small list of order rows into line totals and a report. Learn input, map, reduce, and return with a result you can check.

BrowserJavaScriptArraysCalculations

Before you begin#

  • Use the Browser runtime. This example uses two sample orders and makes no network requests.

WORKFLOW SNAPSHOT

Calculate order totals

4 nodes

Interactive workflow preview loads here. Download the JSON to inspect it in the app.

Import creates an inactive copy. Set your own inputs and connections before running.

Opens as a new, inactive workflow. Review the nodes before running.

Walk through the workflow#

  1. Inspect the Variable node. It provides two orders: two notebooks at 5 each, and three pens at 2 each.
  2. Open Code. input.orders reads the incoming array. map creates a new row for each order; Number turns numeric text into a number before multiplication.
  3. The reduce call adds the line totals, starting at zero. return sends both the new rows and the grand total to the next node.
  4. Run once. Inspect Code for line totals 10 and 6 and a grand total of 16. The last Variable produces Order total: 16.

Understand the script#

const lines = input.orders.map(order => {
  const quantity = Number(order.quantity);
  const price = Number(order.price);
  return {
    name: order.name,
    total: quantity * price,
  };
});
const total = lines.reduce(
  (sum, line) => sum + line.total,
  0
);
return { lines, total };

input is the previous node’s output. map visits each order and returns a new row. reduce keeps a running sum, beginning with the 0 supplied at the end. return makes the result available to the next node.

Check your result#

{
  "lines": [
    { "name": "Notebook", "total": 10 },
    { "name": "Pen", "total": 6 }
  ],
  "total": 16
}

Make one change#

Change the notebook quantity from 2 to 4. Its line total should become 20 and the grand total 26. Set orders to an empty array to get an empty lines array and total 0.

If it does not match#

Check Code’s input before changing the script. input.orders must be an array, and quantity and price must contain numeric values. JavaScript source uses input and variables directly; do not paste double-brace expressions into the code. See Code.