Bird
Raised Fist0
Astroframework~5 mins

Filtering and sorting collections in Astro

Choose your learning style10 modes available
Introduction

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.

Showing only products that are in stock on an online store
Displaying blog posts from a specific category or tag
Sorting a list of events by date so the nearest event shows first
Filtering user comments to show only those with positive feedback
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
This keeps fruits that have the letter 'a'.
Astro
const fruits = ['apple', 'banana', 'cherry'];
const filtered = fruits.filter(fruit => fruit.includes('a'));
This sorts numbers from smallest to largest without changing the original array.
Astro
const numbers = [3, 1, 4, 2];
const sorted = numbers.slice().sort((a, b) => a - b);
This filters products costing more than $15, then sorts them by price low to high.
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>
OutputSuccess
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/5)
1. In Astro, what does filtering a collection do?
const filtered = items.filter(item => item.active);
easy
A. Keeps only items where item.active is true
B. Sorts items alphabetically
C. Removes all items from the collection
D. Duplicates all items in the collection

Solution

  1. Step 1: Understand the filter method

    The filter method keeps items that pass the test inside the function.
  2. Step 2: Analyze the test condition

    The test item => item.active keeps items where active is true.
  3. Final Answer:

    Keeps only items where item.active is true -> Option A
  4. Quick 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
A. filter
B. sort
C. map
D. reduce

Solution

  1. Step 1: Identify the method for sorting

    The method to arrange items in order is sort.
  2. Step 2: Check the syntax

    The syntax numbers.sort((a, b) => a - b) sorts numbers ascending.
  3. Final Answer:

    sort -> Option B
  4. Quick 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
A. ['cherry', 'apple']
B. ['apple', 'cherry']
C. ['banana', 'cherry']
D. ['apple', 'banana', 'cherry']

Solution

  1. Step 1: Filter items with price > 25

    Items kept: apple (50), cherry (30). Banana (20) is removed.
  2. Step 2: Sort filtered items by price ascending

    Sorted order by price: cherry (30), apple (50).
  3. Final Answer:

    ['cherry', 'apple'] -> Option A
  4. Quick 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
A. filter callback should return a boolean
B. data is not an array
C. sort callback must take two arguments, not one
D. Missing semicolon after filter

Solution

  1. Step 1: Check filter usage

    Filter callback returns boolean item.id > 0, which is correct.
  2. Step 2: Check sort usage

    Sort callback must have two parameters to compare, but only one item is given, causing error.
  3. Final Answer:

    sort callback must take two arguments, not one -> Option C
  4. Quick 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:
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
A. Sort by price ascending, then filter duplicates by name
B. Filter products with price < 10, then sort by price
C. Use filter to remove duplicates, then sort by price descending
D. Use a map to track cheapest by name, then convert to array and sort by name

Solution

  1. Step 1: Track cheapest product per name

    Create a map (object) to store the lowest price product for each name by comparing prices.
  2. Step 2: Convert map values to array and sort by name ascending

    Extract products from map, then sort alphabetically by name.
  3. Final Answer:

    Use a map to track cheapest by name, then convert to array and sort by name -> Option D
  4. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard