JavaScript dizileri, herhangi bir ana akım dildeki en zengin metot API'lerinden birine sahiptir. Ancak çoğu öğretici map ve filter'ı yapay örneklerle öğretir — bir dizideki sayıları iki katına çıkarmak, çift sayıları filtrelemek — ve geri kalanını kendiniz çözmenize bırakır. Üretim kodunda gerçekten karşılaşılan metodları gerçekçi verilerle ele alalım: ürünler, siparişler ve kullanıcı kayıtları.
Üzerinde Çalışacağımız Veri Seti
Örnekleri somut tutmak için bu makale boyunca gerçekçi bir ürün kataloğu kullanacağız:
const products = [
{ id: 1, name: 'Wireless Keyboard', category: 'electronics', price: 79.99, rating: 4.5, inStock: true },
{ id: 2, name: 'Mechanical Keyboard', category: 'electronics', price: 149.99, rating: 4.8, inStock: true },
{ id: 3, name: 'USB-C Hub', category: 'electronics', price: 49.99, rating: 4.2, inStock: false },
{ id: 4, name: 'Standing Desk', category: 'furniture', price: 499.99, rating: 4.6, inStock: true },
{ id: 5, name: 'Desk Lamp', category: 'furniture', price: 39.99, rating: 4.1, inStock: true },
{ id: 6, name: 'Monitor Arm', category: 'electronics', price: 89.99, rating: 4.7, inStock: false },
];map() — Her Öğeyi Dönüştürme
Array.prototype.map(), her elemana bir fonksiyon uygulayarak yeni bir dizi oluşturur. Veri dönüşümünün çalışma atıdır — API yanıtlarını kullanıcı arayüzünüzün ihtiyaç duyduğu biçime yeniden şekillendirir:
// Extract just the display data for a product list component
const productCards = products.map(product => ({
id: product.id,
name: product.name,
price: `$${product.price.toFixed(2)}`,
badge: product.inStock ? 'In Stock' : 'Out of Stock',
stars: '★'.repeat(Math.round(product.rating))
}));
// productCards[0] → { id: 1, name: 'Wireless Keyboard', price: '$79.99', badge: 'In Stock', stars: '★★★★★' }
// Apply a discount to all prices
const discounted = products.map(p => ({
...p,
price: parseFloat((p.price * 0.9).toFixed(2)),
originalPrice: p.price
}));map() asla orijinal diziyi değiştirmez — her zaman yeni bir tane döndürür. Bu yüzden zincir oluşturmak güvenlidir ve dönüşüm amaç olduğunda for döngüsü yerine tercih etmelisiniz.
filter() — Alt Küme Alma
filter(), callback'in true döndürdüğü öğeleri içeren yeni bir dizi döndürür:
const inStockProducts = products.filter(p => p.inStock);
const electronicsOnly = products.filter(p => p.category === 'electronics');
const affordableInStock = products.filter(p => p.inStock && p.price < 100);
// Chain map + filter to get display-ready affordable in-stock electronics
const featuredItems = products
.filter(p => p.inStock && p.rating >= 4.5)
.map(p => ({ id: p.id, name: p.name, price: `$${p.price}` }));reduce() — İsviçre Çakısı
Array.prototype.reduce(), imzası korkutucu göründüğü için geliştiricilerin kaçındığı metoddur. Ama bir kez kavrandığında, ona sürekli başvurursunuz. Bir diziyi tek bir değere "indirger" — ve bu değer her şey olabilir: bir sayı, bir nesne, başka bir dizi. İşte gerçekçi bir kullanım durumu: bir diziden arama haritası oluşturma:
// Group products by category (the pattern that makes reduce click)
const byCategory = products.reduce((acc, product) => {
const cat = product.category;
if (!acc[cat]) acc[cat] = [];
acc[cat].push(product);
return acc;
}, {}); // starting value is an empty object
// byCategory.electronics → [Wireless Keyboard, Mechanical Keyboard, USB-C Hub, Monitor Arm]
// byCategory.furniture → [Standing Desk, Desk Lamp]
// Build an id → product lookup (O(1) access instead of .find() on every render)
const productById = products.reduce((acc, p) => {
acc[p.id] = p;
return acc;
}, {});
const keyboard = productById[2]; // instant lookup
// Calculate total cart value
const cart = [{ productId: 1, qty: 2 }, { productId: 4, qty: 1 }];
const cartTotal = cart.reduce((total, item) => {
const product = productById[item.productId];
return total + (product.price * item.qty);
}, 0);
// 79.99 * 2 + 499.99 * 1 = 659.97reduce()'u yalnızca sayıları toplamak için kullanıyorsanız daha temiz bir alternatif düşünün: products.reduce((sum, p) => sum + p.price, 0) basit durumlar için uygundur. Ancak gruplama ve dizinleme için reduce() rakipsizdir.find() ve findIndex() — İlk Eşleşmede Durma
Çok yaygın bir hata, yalnızca bir öğeye ihtiyaç duyduğunuzda filter() kullanmaktır. filter() her zaman tüm diziyi tarar. find() bir eşleşme bulur bulmaz durur — en iyi durumda O(1) buna karşın filter için O(n):
// ❌ Returns an array, scans everything even after finding a match
const found = products.filter(p => p.id === 3)[0];
// ✅ Returns the item directly, stops at first match
const product = products.find(p => p.id === 3);
// { id: 3, name: 'USB-C Hub', ... }
// findIndex() — gives you the position (useful for updates and deletions)
const idx = products.findIndex(p => p.id === 3);
// Update immutably:
const updated = [
...products.slice(0, idx),
{ ...products[idx], inStock: true },
...products.slice(idx + 1)
];some() ve every() — Boolean Kontrolleri
Bir dizinin içeriği hakkında evet/hayır yanıtına ihtiyaç duyduğunuzda, some() ve every(), filtreleme ve uzunluğu kontrol etmekten daha temizdir:
const hasOutOfStock = products.some(p => !p.inStock); // true
const allHighRated = products.every(p => p.rating >= 4.0); // true
const allInStock = products.every(p => p.inStock); // false
// Common pattern: form validation
const formFields = [
{ name: 'email', value: '[email protected]', valid: true },
{ name: 'password', value: '', valid: false },
{ name: 'username', value: 'dev123', valid: true }
];
const isFormValid = formFields.every(field => field.valid); // false
const hasAnyError = formFields.some(field => !field.valid); // trueflat() ve flatMap() — İç İçe Dizileri İşleme
API'niz iç içe diziler döndürdüğünde, flat() ve flatMap() bunları tek bir seviyeye daraltır. flatMap(), bir map işleminin girdi başına sıfır, bir veya birden fazla öğe üretebileceği durumlarda özellikle kullanışlıdır:
// flat() — collapse one level of nesting
const orderLines = [
['Wireless Keyboard', 'USB-C Hub'],
['Standing Desk'],
['Mechanical Keyboard', 'Monitor Arm', 'Desk Lamp']
];
const allItems = orderLines.flat();
// ['Wireless Keyboard', 'USB-C Hub', 'Standing Desk', 'Mechanical Keyboard', ...]
// flatMap() — map + flat in one pass (more efficient than chaining)
const ordersWithTags = [
{ id: 101, items: ['keyboard', 'hub'], tags: ['electronics'] },
{ id: 102, items: ['desk', 'lamp'], tags: ['furniture', 'sale'] },
];
// Get all unique tags across all orders
const allTags = ordersWithTags.flatMap(order => order.tags);
// ['electronics', 'furniture', 'sale']
// Filter-and-extract in one pass with flatMap
const expensiveNames = products.flatMap(p =>
p.price > 100 ? [p.name] : [] // return empty array to skip, or [value] to include
);
// ['Mechanical Keyboard', 'Standing Desk']Array.from() — Dizi Benzeri Şeyleri Dönüştürme
Array.from(), yinelenebilir her şeyi gerçek bir diziye dönüştürür. Bu, DOM NodeList'leri, Set'ler, Map'ler ve üretici sonuçlarıyla sürekli karşımıza çıkar:
// Convert a NodeList to an array so you can use .map() and .filter()
const checkboxes = Array.from(document.querySelectorAll('input[type="checkbox"]'));
const checkedValues = checkboxes
.filter(el => el.checked)
.map(el => el.value);
// Deduplicate an array using Set → Array.from
const tags = ['electronics', 'sale', 'electronics', 'new', 'sale'];
const unique = Array.from(new Set(tags));
// ['electronics', 'sale', 'new']
// Create a range (like Python's range())
const range = Array.from({ length: 5 }, (_, i) => i + 1);
// [1, 2, 3, 4, 5]
// Extract Map entries for further processing
const priceMap = new Map(products.map(p => [p.id, p.price]));
const prices = Array.from(priceMap.values()); // [79.99, 149.99, ...]Doğru Sıralama
Varsayılan sort() her şeyi stringe dönüştürür; bu, sayıların yanlış sıralanması ve ASCII dışı karakterler için string sıralamasının bozulması anlamına gelir. Her zaman bir karşılaştırıcı geçirin:
// ❌ Default sort — wrong for numbers
[10, 9, 100, 2].sort(); // [10, 100, 2, 9] ← string order
// ✅ Numeric sort
[10, 9, 100, 2].sort((a, b) => a - b); // [2, 9, 10, 100] ascending
[10, 9, 100, 2].sort((a, b) => b - a); // [100, 10, 9, 2] descending
// Sort products by price ascending
const byPrice = [...products].sort((a, b) => a.price - b.price);
// Sort by name — use localeCompare for proper string ordering
const byName = [...products].sort((a, b) =>
a.name.localeCompare(b.name, 'en', { sensitivity: 'base' })
);
// Multi-key sort: category first, then rating descending
const sorted = [...products].sort((a, b) => {
if (a.category !== b.category) return a.category.localeCompare(b.category);
return b.rating - a.rating;
});sort() orijinal diziyi değiştirir. Orijinal sırayı korumak istiyorsanız her zaman önce spread kullanın ([...products].sort(...)).Object.groupBy() — ES2024 Gruplama
ES2024'ten önce dizileri gruplamak için reduce() kullanılırdı (daha önce gösterildiği gibi). Artık yerleşik bir yöntem var: Object.groupBy(). Basit gruplama durumları için daha temizdir:
// Group products by category — ES2024
const grouped = Object.groupBy(products, p => p.category);
// {
// electronics: [Wireless Keyboard, Mechanical Keyboard, USB-C Hub, Monitor Arm],
// furniture: [Standing Desk, Desk Lamp]
// }
// Group by stock status
const byStock = Object.groupBy(products, p => p.inStock ? 'available' : 'unavailable');
// Group orders by month
const orders = [
{ id: 1, date: new Date('2026-01-15'), total: 129.99 },
{ id: 2, date: new Date('2026-01-22'), total: 49.99 },
{ id: 3, date: new Date('2026-02-05'), total: 89.99 },
];
const byMonth = Object.groupBy(orders, o =>
o.date.toLocaleString('en', { month: 'long', year: 'numeric' })
);Object.groupBy(), Node.js 21+ ve 2024 ortasından itibaren tüm modern tarayıcılarda mevcuttur. Güncel uyumluluk için MDN groupBy referansını kontrol edin. Eski ortamlar için reduce() kalıbı hâlâ çalışır.
Kullanışlı Araçlar
API'lerden JSON veri dizileriyle çalışırken bu araçlar gerçek zaman kazandırır: Derinden iç içe geçmiş yükleri incelemek için JSON Formatter, büyük dizilerden belirli alanları sorgulamak için JSON Path, ve metot zinciri kodunu temizlemek için JS Formatter. Tam MDN Dizi referansı sık kullanılanlara eklenmeye değer — çoğu geliştiricinin bildiğinden daha fazla metot vardır.
Sonuç
JavaScript'in dizi metodları, bir yardımcı program kütüphanesine başvuracağınız işlemlerin çoğunu karşılar. Dönüştürme ve alt küme alma için map() ve filter(), gruplama ve dizinleme için reduce(), aramalar için filter()[0] yerine find(), tek geçişte filtrele-ve-dönüştür için flatMap(), ve modern ortamlarda temiz gruplama için Object.groupBy(). Kilit nokta, iş için doğru aracı kullanmak — ve çoğu döngünün iyi seçilmiş bir metotla değiştirilebileceğini bilmektir.