Implementing the Summary

JavaScriptJavaScriptBeginner
Practice Now

Introduction

In this lab, set in the bustling startup scene of "FinTech Valley", you'll step into the shoes of Alex, a budding software engineer tasked with enhancing the financial tracking system for a rapidly growing tech company. The company's financial team needs a dynamic way to view the overall financial health of the organization. Your goal is to implement a feature in their existing web-based accounting application that calculates and displays the total income, total expenses, and net balance, providing real-time financial insights.

Knowledge Points:

  • Array.prototype.filter()
  • Array.prototype.reduce()

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/DOMManipulationGroup(["`DOM Manipulation`"]) javascript(("`JavaScript`")) -.-> javascript/ToolsandEnvironmentGroup(["`Tools and Environment`"]) javascript(("`JavaScript`")) -.-> javascript/NetworkingGroup(["`Networking`"]) javascript(("`JavaScript`")) -.-> javascript/SecurityGroup(["`Security`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") javascript/BasicConceptsGroup -.-> javascript/functions("`Functions`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/BasicConceptsGroup -.-> javascript/obj_manip("`Object Manipulation`") javascript/AdvancedConceptsGroup -.-> javascript/closures("`Closures`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/template_lit("`Template Literals`") javascript/DOMManipulationGroup -.-> javascript/dom_select("`DOM Selection`") javascript/DOMManipulationGroup -.-> javascript/dom_manip("`DOM Manipulation`") javascript/DOMManipulationGroup -.-> javascript/event_handle("`Event Handling`") javascript/ToolsandEnvironmentGroup -.-> javascript/bom("`Browser Object Model`") javascript/ToolsandEnvironmentGroup -.-> javascript/web_storage("`Web Storage`") javascript/NetworkingGroup -.-> javascript/json("`JSON`") javascript/SecurityGroup -.-> javascript/xss("`Cross-Site Scripting`") subgraph Lab Skills javascript/variables -.-> lab-290732{{"`Implementing the Summary`"}} javascript/data_types -.-> lab-290732{{"`Implementing the Summary`"}} javascript/arith_ops -.-> lab-290732{{"`Implementing the Summary`"}} javascript/comp_ops -.-> lab-290732{{"`Implementing the Summary`"}} javascript/loops -.-> lab-290732{{"`Implementing the Summary`"}} javascript/functions -.-> lab-290732{{"`Implementing the Summary`"}} javascript/array_methods -.-> lab-290732{{"`Implementing the Summary`"}} javascript/obj_manip -.-> lab-290732{{"`Implementing the Summary`"}} javascript/closures -.-> lab-290732{{"`Implementing the Summary`"}} javascript/higher_funcs -.-> lab-290732{{"`Implementing the Summary`"}} javascript/template_lit -.-> lab-290732{{"`Implementing the Summary`"}} javascript/dom_select -.-> lab-290732{{"`Implementing the Summary`"}} javascript/dom_manip -.-> lab-290732{{"`Implementing the Summary`"}} javascript/event_handle -.-> lab-290732{{"`Implementing the Summary`"}} javascript/bom -.-> lab-290732{{"`Implementing the Summary`"}} javascript/web_storage -.-> lab-290732{{"`Implementing the Summary`"}} javascript/json -.-> lab-290732{{"`Implementing the Summary`"}} javascript/xss -.-> lab-290732{{"`Implementing the Summary`"}} end

Filter and Reduce

JavaScript's Array.prototype.filter() and Array.prototype.reduce() methods are powerful tools for array manipulation, making data processing more efficient and concise. These methods are used to filter elements in an array and to accumulate values of array elements, respectively.

Filter

The filter() method creates a new array with all elements that pass the test implemented by the provided function. It does not alter the original array but returns a new array.

Syntax:

let result = array.filter(function (element, index, array) {
  // Test condition
  return true; // or false
});
  • element: The current element being processed in the array.
  • index (optional): The index of the current element.
  • array (optional): The array upon which filter is called.

For example, filtering numbers greater than 10.

let numbers = [5, 12, 8, 130, 44];
let filtered = numbers.filter(function (number) {
  return number > 10;
});
console.log(filtered); // Output: [12, 130, 44]
Reduce

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

Syntax:

let result = array.reduce(function (
  accumulator,
  currentValue,
  currentIndex,
  array
) {
  // Return the accumulated result
  return accumulator + currentValue;
}, initialValue);
  • accumulator: Accumulates the callback's return values; it is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied.
  • currentValue: The current element being processed in the array.
  • currentIndex (optional): The index of the current element being processed.
  • array (optional): The array reduce was called upon.

For example, calculating the sum of all numbers in an array.

let numbers = [5, 12, 8, 130, 44];
let total = numbers.reduce(function (accumulator, number) {
  return accumulator + number;
}, 0);
console.log(total); // Output: 199

With the use of these two methods in mind, the next step is to calculate the total of your income and expenditure.

Implement Summary Calculation Logic

In this step, you will implement the logic to calculate the total income, total expenses, and balance. This involves adding JavaScript functions that iterate over the transaction records, sum up the income and expenses, and calculate the net balance.

Write the following in script.js:

document.addEventListener("DOMContentLoaded", function () {
  const updateSummary = () => {
    const totalIncome = records
      .filter((record) => record.type === "income")
      .reduce((acc, record) => acc + parseFloat(record.amount), 0);
    const totalExpense = records
      .filter((record) => record.type === "expense")
      .reduce((acc, record) => acc + parseFloat(record.amount), 0);
    const balance = totalIncome - totalExpense;

    totalIncomeEl.textContent = `Total Income: ${totalIncome}`;
    totalExpenseEl.textContent = `Total Expense: ${totalExpense}`;
    balanceEl.textContent = `Balance: ${balance}`;
  };

  // Function to save records to localStorage and update the UI
  const saveRecords = () => {
    localStorage.setItem("records", JSON.stringify(records));
    renderRecords();
    updateSummary();
  };
  renderRecords();
  updateSummary();
});

This JavaScript function, updateSummary, calculates the total income and expenses from the records array and updates the balance. It then updates the text content of the respective HTML elements in the summary section.

Summary

In this lab, you embarked on a journey through the financial landscape of a startup company in "FinTech Valley". You played the role of Alex, enhancing a web-based accounting tool to provide real-time financial summaries. By integrating a dynamic summary feature, you enabled the financial team to gain immediate insights into the company's financial status, illustrating the power of combining HTML, CSS, and JavaScript to create interactive and informative web applications. Through this experience, you learned how to manipulate the DOM using JavaScript and improved your understanding of real-world application development.

Other JavaScript Tutorials you may like