Practical JavaScript: Array Methods in Action
JavaScript array methods aren’t just theoretical—they shine when handling real data. Let’s see some hands-on examples.
1. Fetching and Processing API Data
Imagine you fetch a list of users from an API:
async function fetchUsers() {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const users = await response.json();
return users;
}a) Extract Names with map()
fetchUsers().then(users => {
const names = users.map(user => user.name);
console.log(names);
});Output: An array of user names.
b) Filter Users by City with filter()
fetchUsers().then(users => {
const filtered = users.filter(user => user.address.city === "South Christy");
console.log(filtered);
});Output: Only users from “South Christy”.
c) Find a User by ID with find()
fetchUsers().then(users => {
const user = users.find(u => u.id === 5);
console.log(user);
});Output: The user object with ID 5.
d) Summarize Data with reduce()
Count users by company:
fetchUsers().then(users => {
const companies = users.reduce((acc, user) => {
const company = user.company.name;
acc[company] = (acc[company] || 0) + 1;
return acc;
}, {});
console.log(companies);
});Output:
{ "Romaguera-Crona": 1, "Deckow-Crist": 1, ... }
2. Building a Simple To-Do List
Suppose you have a to-do list:
let todos = [
{ id: 1, task: "Buy groceries", completed: true },
{ id: 2, task: "Write blog post", completed: false },
{ id: 3, task: "Go jogging", completed: false },
];a) Get Pending Tasks
const pending = todos.filter(todo => !todo.completed);
console.log(pending);b) Mark a Task Complete
todos = todos.map(todo =>
todo.id === 2 ? { ...todo, completed: true } : todo
);
console.log(todos);c) Remove a Task
todos = todos.filter(todo => todo.id !== 1);
console.log(todos);d) Count Completed Tasks
const completedCount = todos.reduce(
(count, todo) => (todo.completed ? count + 1 : count),
0
);
console.log(completedCount); // 2
3. Sorting Tasks
Sort tasks alphabetically:
todos.sort((a, b) => a.task.localeCompare(b.task));
console.log(todos);
Key Takeaways
map→ transform datafilter→ pick what you needreduce→ summarize or aggregatefind→ locate a single elementsort→ reorder elements
By combining these methods, you can efficiently manipulate real-world datasets and manage app state cleanly.