Powerful Array Operations
Modern JavaScript has many built-in array methods that make working with arrays easier and more efficient.
These methods allow you to transform, filter, and process arrays without writing manual loops.
Example
const numbers = [1, 2, 3, 4, 5];
// map - Transform each element
const doubled = numbers.map(num => num * 2);
// [2, 4, 6, 8, 10]
// filter - Keep elements that pass test
const evens = numbers.filter(num => num % 2 === 0);
// [2, 4]
// find - Get first element that matches
const firstEven = numbers.find(num => num % 2 === 0);
// 2
// reduce - Reduce to single value
const sum = numbers.reduce((total, num) => total + num, 0);
// 15
// forEach - Loop through array
numbers.forEach(num => console.log(num));
// some - Check if any element passes test
const hasEven = numbers.some(num => num % 2 === 0);
// true
// every - Check if all elements pass test
const allPositive = numbers.every(num => num > 0);
// true
// sort - Sort array
const unsorted = [3, 1, 4, 1, 5, 9, 2, 6];
unsorted.sort((a, b) => a - b); // Ascending
// [1, 1, 2, 3, 4, 5, 6, 9]
// Chaining methods
const result = numbers
.filter(num => num > 2)
.map(num => num * 2)
.reduce((sum, num) => sum + num, 0);
// (3+4+5) * 2 = 24 - map() - Transform each element
- filter() - Keep matching elements
- find() - Find first match
- reduce() - Reduce to single value
- forEach() - Loop through each
- some() - Test if any match
- every() - Test if all match
- sort() - Sort array
- Methods can be chained!
Try Array Methods
HTML
<div class="array-methods-demo">
<h3>Student Grades</h3>
<p>Grades: [85, 92, 78, 95, 88, 73, 90]</p>
<button onclick="showStats()">Show Statistics</button>
<button onclick="filterGrades()">Filter Grades</button>
<div id="statsOutput"></div>
<hr style="margin: 20px 0;">
<h3>Product Prices</h3>
<p>Prices: [$10, $25, $15, $30, $20]</p>
<button onclick="applyDiscount()">Apply 20% Discount</button>
<button onclick="findExpensive()">Find Expensive (>$20)</button>
<div id="priceOutput"></div>
</div> CSS
.array-methods-demo { padding: 20px; background: #f0f0f0; border-radius: 8px; }
button { padding: 10px 15px; background: #d1039e; color: white; border: none; border-radius: 5px; cursor: pointer; margin: 5px; font-size: 14px; }
#statsOutput, #priceOutput { margin-top: 15px; padding: 15px; background: white; border-radius: 5px; line-height: 1.8; } JavaScript
const grades = [85, 92, 78, 95, 88, 73, 90];
const prices = [10, 25, 15, 30, 20];
function showStats() {
const output = document.getElementById('statsOutput');
const average = grades.reduce((sum, grade) => sum + grade, 0) / grades.length;
const highest = Math.max(...grades);
const lowest = Math.min(...grades);
const passing = grades.filter(g => g >= 70).length;
const allPassing = grades.every(g => g >= 70);
output.innerHTML = `
<strong>Grade Statistics:</strong><br>
Average: ${average.toFixed(2)}<br>
Highest: ${highest}<br>
Lowest: ${lowest}<br>
Passing (≥70): ${passing} out of ${grades.length}<br>
All Passing: ${allPassing ? 'Yes ✓' : 'No ✗'}
`;
}
function filterGrades() {
const output = document.getElementById('statsOutput');
const excellent = grades.filter(g => g >= 90);
const good = grades.filter(g => g >= 80 && g < 90);
const average = grades.filter(g => g >= 70 && g < 80);
const failing = grades.filter(g => g < 70);
output.innerHTML = `
<strong>Grade Distribution:</strong><br>
Excellent (90-100): ${excellent.join(', ') || 'None'}<br>
Good (80-89): ${good.join(', ') || 'None'}<br>
Average (70-79): ${average.join(', ') || 'None'}<br>
Failing (<70): ${failing.join(', ') || 'None'}
`;
}
function applyDiscount() {
const output = document.getElementById('priceOutput');
const discounted = prices.map(price => price * 0.8);
output.innerHTML = `
<strong>Prices After 20% Discount:</strong><br>
Original: $${prices.join(', $')}<br>
Discounted: $${discounted.map(p => p.toFixed(2)).join(', $')}
`;
}
function findExpensive() {
const output = document.getElementById('priceOutput');
const expensive = prices.filter(price => price > 20);
const total = prices.reduce((sum, price) => sum + price, 0);
output.innerHTML = `
<strong>Price Analysis:</strong><br>
Expensive items (>$20): $${expensive.join(', $')}<br>
Total of all items: $${total}<br>
Average price: $${(total / prices.length).toFixed(2)}
`;
} Notes
- Array methods are incredibly powerful! Master map, filter, and reduce - they're used everywhere in modern JavaScript.
