0
0
DSA Javascriptprogramming~30 mins

BST vs Hash Map Trade-offs for Ordered Data in DSA Javascript - Build Both Approaches

Choose your learning style9 modes available
BST vs Hash Map Trade-offs for Ordered Data
📖 Scenario: Imagine you are managing a small library's book collection. You want to store book titles and their number of copies. You need to quickly find how many copies a book has, but sometimes you also want to see all books sorted by title.
🎯 Goal: You will create a simple data structure to store books and their copies. Then, you will add a way to get all books sorted by title. This will help you understand when to use a Binary Search Tree (BST) or a Hash Map for storing ordered data.
📋 What You'll Learn
Create a JavaScript object called bookCopies with exact book titles as keys and their copies as values.
Create a variable called sortedTitles to hold the sorted list of book titles.
Use a method to get all book titles from bookCopies and sort them alphabetically.
Print the sorted list of book titles.
💡 Why This Matters
🌍 Real World
Libraries, stores, and many apps need to store items with quick lookup and sometimes sorted order for display.
💼 Career
Understanding when to use hash maps or trees helps in building efficient software for searching and sorting data.
Progress0 / 4 steps
1
Create the bookCopies object
Create a JavaScript object called bookCopies with these exact entries: 'The Hobbit': 5, '1984': 8, 'Brave New World': 3, 'Fahrenheit 451': 6, 'Animal Farm': 4.
DSA Javascript
Hint

Use curly braces {} to create an object. Each book title is a key in quotes, followed by a colon and the number of copies.

2
Create sortedTitles variable
Create a variable called sortedTitles and set it to an empty array [].
DSA Javascript
Hint

Use let to create a variable that can change later. Set it to an empty array [].

3
Get and sort book titles
Set sortedTitles to the list of keys from bookCopies sorted alphabetically using Object.keys(bookCopies).sort().
DSA Javascript
Hint

Use Object.keys() to get all keys from the object, then use .sort() to sort them alphabetically.

4
Print the sorted book titles
Print the sortedTitles array using console.log(sortedTitles).
DSA Javascript
Hint

Use console.log() to print the array to the console.