By the end of this lesson, you will understand how to find total sort values in JavaScript. You will achieve this using methods like find, reduce, and sort.
JavaScript arrays allow you to hold multiple values. Often, you might want to find total sort values in your applications. For instance, consider a shopping list:
In this example, you could want to find the price of a specific fruit, total all prices, or sort them by price. Therefore, understanding these operations is crucial for your coding skills.
File: shopping.js
const fruits = [
{ name: 'Apples', price: 2 },
{ name: 'Bananas', price: 1 },
{ name: 'Oranges', price: 3 }
];
// Find the price of Bananas
const banana = fruits.find(fruit => fruit.name === 'Bananas');
console.log('Banana Price:', banana.price);
// Total price of all fruits
const totalPrice = fruits.reduce((total, fruit) => total + fruit.price, 0);
console.log('Total Price:', totalPrice);
// Sort fruits by price
const sortedFruits = fruits.sort((a, b) => a.price - b.price);
console.log('Sorted Fruits:', sortedFruits);
Banana Price: 1
Total Price: 6
Sorted Fruits: [ { name: 'Bananas', price: 1 }, { name: 'Apples', price: 2 }, { name: 'Oranges', price: 3 } ]
In the code, we first create an array of fruit objects. Each object has a name and a price. Next, we use find to search for the price of Bananas. Additionally, reduce helps add all fruit prices to get a total. Finally, sort arranges the fruits by their prices in ascending order.
Now it’s your turn! Create an array of five book objects. Each book should have a title and a price. Then:
These skills are essential for your future projects. For a deeper understanding of JavaScript, consider reviewing What Is JavaScript? Examples from Everyday Websites.
const books = [
{ title: 'Book A', price: 10 },
{ title: 'Book B', price: 15 },
{ title: 'Book C', price: 5 },
{ title: 'Book D', price: 20 },
{ title: 'Book E', price: 12 }
];
// Find the price of Book B
const bookB = books.find(book => book.title === 'Book B');
console.log('Book B Price:', bookB.price);
// Total price of all books
const totalBookPrice = books.reduce((total, book) => total + book.price, 0);
console.log('Total Price of Books:', totalBookPrice);
// Sort books by price
const sortedBooks = books.sort((a, b) => a.price - b.price);
console.log('Sorted Books:', sortedBooks);
const keyword for arrays and objects.find, reduce, and sort. It’s crucial to check for typos.find to locate specific items in an array.reduce to calculate totals of array values.sort to order items based on certain criteria.