JavaScript
JavaScript Arrays Methods Utilities
JavaScript Array Methods - Common Patterns
Useful JavaScript array method patterns and examples for common data manipulation tasks.
Common JavaScript array method patterns for data manipulation.
Filter and Map
// Get active users' names
const activeUserNames = users
.filter(user => user.active)
.map(user => user.name);
// Usage
const users = [
{ name: 'John', active: true },
{ name: 'Jane', active: false },
{ name: 'Bob', active: true },
];
// Result: ['John', 'Bob']
Reduce to Object
// Group items by category
const grouped = items.reduce((acc, item) => {
const category = item.category;
if (!acc[category]) {
acc[category] = [];
}
acc[category].push(item);
return acc;
}, {});
// Usage
const items = [
{ name: 'Apple', category: 'fruit' },
{ name: 'Carrot', category: 'vegetable' },
];
// Result: { fruit: [...], vegetable: [...] }
Find and Replace
// Update item in array
const updated = items.map(item =>
item.id === targetId ? { ...item, ...updates } : item
);
// Usage
const items = [{ id: 1, name: 'Old' }];
const updated = items.map(item =>
item.id === 1 ? { ...item, name: 'New' } : item
);
Remove Duplicates
// Remove duplicates by property
const unique = items.filter((item, index, self) =>
index === self.findIndex(t => t.id === item.id)
);
// Or using Set
const unique = [...new Set(items.map(item => item.id))]
.map(id => items.find(item => item.id === id));
Sort by Multiple Criteria
// Sort by multiple properties
const sorted = items.sort((a, b) => {
if (a.category !== b.category) {
return a.category.localeCompare(b.category);
}
return a.name.localeCompare(b.name);
});
Features
- Functional programming patterns
- Immutable operations
- Efficient algorithms
- Readable code