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()
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.
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.
We use cookies for a number of reasons, such as keeping the website reliable and secure, to improve your experience on our website and to see how you interact with it. By accepting, you agree to our use of such cookies. Privacy Policy