Array Iteration
π¨βπΌ We need to process our inventory data. Let's practice different ways to
iterate over arrays.
- Use
for...ofto log each product - Find all products that are in stock
- Count products over a certain price
π°
for...of with type inference:for (const product of products) {
// TypeScript knows product is { name: string, price: number, ... }
console.log(product.name)
}
π° Building a filtered list:
const inStock: ProductType[] = []
for (const product of products) {
if (product.inStock) {
inStock.push(product)
}
}
π MDN - for...of