Filtering and sorting collections help you organize and show only the data you want in the order you want. It makes your app easier to use and understand.
Filtering and sorting collections in Astro
Introduction
Syntax
Astro
const filtered = collection.filter(item => condition); const sorted = collection.slice().sort((a, b) => a.property - b.property);
Use
filter() to keep items that match a condition.Use
sort() to order items by a property or value. Use slice() to copy the array before sorting if you want to keep the original order.Examples
Astro
const fruits = ['apple', 'banana', 'cherry']; const filtered = fruits.filter(fruit => fruit.includes('a'));
Astro
const numbers = [3, 1, 4, 2]; const sorted = numbers.slice().sort((a, b) => a - b);
Astro
const products = [
{ name: 'Shirt', price: 20 },
{ name: 'Hat', price: 10 },
{ name: 'Shoes', price: 50 }
];
const filtered = products.filter(p => p.price > 15);
const sorted = filtered.slice().sort((a, b) => a.price - b.price);Sample Program
This Astro component filters products to show only those in stock, then sorts them by price from low to high. It then displays the list in an unordered list.
Astro
---
const products = [
{ name: 'Book', price: 15, inStock: true },
{ name: 'Pen', price: 5, inStock: false },
{ name: 'Notebook', price: 10, inStock: true }
];
const availableProducts = products.filter(product => product.inStock);
const sortedProducts = availableProducts.slice().sort((a, b) => a.price - b.price);
---
<ul>
{sortedProducts.map(product => (
<li>{product.name} - ${product.price}</li>
))}
</ul>Important Notes
Filtering does not change the original collection; it creates a new one.
Sorting changes the order of the collection in place, so copy it first if you need the original order.
Use simple conditions in filter() for clear and readable code.
Summary
Filtering keeps only items you want based on a test.
Sorting arranges items in a specific order.
Use these together to show clean, organized lists in your app.
Practice
1. In Astro, what does filtering a collection do?
const filtered = items.filter(item => item.active);easy
Solution
Step 1: Understand the filter method
Thefiltermethod keeps items that pass the test inside the function.Step 2: Analyze the test condition
The testitem => item.activekeeps items whereactiveis true.Final Answer:
Keeps only items whereitem.activeis true -> Option AQuick Check:
Filtering = keeping matching items [OK]
Hint: Filter keeps items passing the test function [OK]
Common Mistakes:
- Thinking filter sorts items
- Assuming filter removes all items
- Confusing filter with map
2. Which of these is the correct syntax to sort an array of numbers in ascending order in Astro's JavaScript code?
const numbers = [3, 1, 4]; const sorted = numbers._____((a, b) => a - b);
easy
Solution
Step 1: Identify the method for sorting
The method to arrange items in order issort.Step 2: Check the syntax
The syntaxnumbers.sort((a, b) => a - b)sorts numbers ascending.Final Answer:
sort -> Option BQuick Check:
Sorting method = sort [OK]
Hint: Use .sort() with compare function to order numbers [OK]
Common Mistakes:
- Using filter instead of sort
- Using map which transforms but doesn't sort
- Using reduce which aggregates values
3. What will be the output of this Astro JavaScript code?
const items = [
{ name: 'apple', price: 50 },
{ name: 'banana', price: 20 },
{ name: 'cherry', price: 30 }
];
const filteredSorted = items
.filter(item => item.price > 25)
.sort((a, b) => a.price - b.price);
console.log(filteredSorted.map(i => i.name));medium
Solution
Step 1: Filter items with price > 25
Items kept: apple (50), cherry (30). Banana (20) is removed.Step 2: Sort filtered items by price ascending
Sorted order by price: cherry (30), apple (50).Final Answer:
['cherry', 'apple'] -> Option AQuick Check:
Filter then sort = ['cherry', 'apple'] [OK]
Hint: Filter first, then sort to get ordered filtered list [OK]
Common Mistakes:
- Including banana which fails filter
- Sorting descending instead of ascending
- Not mapping to names before output
4. This Astro code tries to filter and sort a list but causes an error. What is the problem?
const data = [{id: 1}, {id: 2}];
const result = data.filter(item => item.id > 0).sort(item => item.id);
console.log(result);medium
Solution
Step 1: Check filter usage
Filter callback returns booleanitem.id > 0, which is correct.Step 2: Check sort usage
Sort callback must have two parameters to compare, but only oneitemis given, causing error.Final Answer:
sort callback must take two arguments, not one -> Option CQuick Check:
Sort needs two args for comparison [OK]
Hint: Sort callback needs two parameters (a, b) [OK]
Common Mistakes:
- Using one parameter in sort callback
- Confusing filter and sort callbacks
- Assuming missing semicolon causes error
5. You have a list of products with possible duplicate names but different prices:
How do you filter to keep only the cheapest product for each name, then sort the result by name ascending?
const products = [
{ name: 'pen', price: 10 },
{ name: 'pen', price: 5 },
{ name: 'notebook', price: 15 },
{ name: 'pen', price: 7 }
];How do you filter to keep only the cheapest product for each name, then sort the result by name ascending?
hard
Solution
Step 1: Track cheapest product per name
Create a map (object) to store the lowest price product for each name by comparing prices.Step 2: Convert map values to array and sort by name ascending
Extract products from map, then sort alphabetically byname.Final Answer:
Use a map to track cheapest by name, then convert to array and sort by name -> Option DQuick Check:
Map for cheapest + sort by name = correct [OK]
Hint: Use map to keep cheapest, then sort by name [OK]
Common Mistakes:
- Filtering by price without grouping by name
- Sorting before removing duplicates
- Removing duplicates without checking price
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
