Master lists, iteration, filtering, and sorting
Arrays are ordered lists of values. Think of them as shopping lists, ingredient collections, or recipe steps - any time you need to store multiple related items in a specific order!
๐ก Real-World Example:
Your shopping list: ["eggs", "milk", "flour", "sugar"] - each item has a position (index) starting from 0!
const ingredients = ["flour", "sugar", "eggs"];
console.log(ingredients[0]); // "flour" (first item)
console.log(ingredients.length); // 3 (total items)
const pantry = ["rice", "beans"];
pantry.push("pasta"); // Add to end: ["rice", "beans", "pasta"]
pantry.unshift("bread"); // Add to start: ["bread", "rice", "beans", "pasta"]
pantry.pop(); // Remove from end: ["bread", "rice", "beans"]
pantry.shift(); // Remove from start: ["rice", "beans"]
const calories = [100, 250, 50, 400, 150];
const lowCal = calories.filter(cal => cal < 200);
console.log(lowCal); // [100, 50, 150]
const prices = [10, 20, 30];
const withTax = prices.map(price => price * 1.1);
console.log(withTax); // [11, 22, 33]
const ratings = [4, 2, 5, 1, 3];
ratings.sort((a, b) => a - b); // Ascending: [1, 2, 3, 4, 5]
ratings.sort((a, b) => b - a); // Descending: [5, 4, 3, 2, 1]
let nums = [3, 1, 4, 1, 5];
nums.sort(); // [1, 1, 3, 4, 5]
// Sort numbers properly
nums.sort((a, b) => a - b);
let items = [1, 2, 3, 4, 5];
let part = items.slice(1, 4);
// [2, 3, 4]
let arr = [1, 2, 3];
arr.reverse();
// [3, 2, 1]
let a = [1, 2];
let b = [3, 4];
let c = a.concat(b);
// [1, 2, 3, 4]
Organize your weekly meals! Use filter, sort, and map methods to manage your meal plan efficiently.
Manage a restaurant order queue! Practice push, shift, and array manipulation to process orders efficiently.
Filter meals based on max calories and sort by preparation time:
Example meals:
[{name: "Salad", calories: 150, prepTime: 10}, ...]
With maxCalories=200:
โ ["Salad", "Soup"] (sorted by prepTime)
๐ก Hints:
.filter() to
select meals
.sort() with
comparison function
.map() to
extract names
Manage a restaurant order queue:
Example:
processQueue(["Order1", "Order2"], "Order3", true)
โ ["Order2", "Order3"] (served Order1, added Order3)
๐ก Hints:
.push() to
add to end
.shift() to
remove from start
[...queue]