USD ($)
$
United States Dollar
Euro Member Countries
India Rupee

Arrays and Objects

Lesson 18/30 | Study Time: 25 Min

Arrays and objects are core data structures used to store and organize data in programming, especially in JavaScript.

Arrays hold ordered collections of values, while objects store data as key–value pairs, making them ideal for representing real-world entities.

Methods such as map, filter, and reduce provide powerful ways to process and transform array data in a clean, functional style.

Destructuring simplifies extracting values from arrays and objects, improving code readability and reducing repetitive syntax. 

JavaScript Arrays: The Foundation

Arrays store ordered collections of data, perfect for lists like user profiles or shopping carts.

Modern methods replace traditional for loops with concise, declarative code that's easier to read and less error-prone.

Core Array Methods: map, filter, reduce

These three methods transform data without mutating the original array—a best practice for predictable code.


1. map() creates a new array by applying a function to each element.

2. filter() returns elements passing a test.

3. reduce() boils an array down to a single value.

javascript
const numbers = [1, 2, 3, 4, 5];

// map: Double each number
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10]

// filter: Get even numbers only
const evens = numbers.filter(n => n % 2 === 0); // [2, 4]

// reduce: Sum all numbers
const sum = numbers.reduce((acc, n) => acc + n, 0); // 15


Practical Example: Process a user list for a dashboard.

Chain Them Together

javascript
const users = [
{name: 'Alice', score: 85},
{name: 'Bob', score: 92},
{name: 'Charlie', score: 78}
];

const topNames = users
.filter(user => user.score > 80)
.map(user => user.name.toUpperCase())
.sort(); // ['ALICE', 'BOB']

Common Array Patterns and Pitfalls


Real-World Use Case: E-commerce cart totals 

javascript
const cart = [
{item: 'Shirt', price: 20, qty: 2},
{item: 'Shoes', price: 50, qty: 1}
];

const total = cart
.map(item => item.price * item.qty)
.reduce((sum, cost) => sum + cost, 0); // 90

JavaScript Objects: Key-Value Powerhouses


Objects store related data as key-value pairs, like user profiles {name: 'John', age: 30}. They're the building blocks of JSON APIs and state management.


Object Methods and Iteration

Access properties with dot (.) or bracket ([]) notation. ES6+ adds cleaner iteration.


1. Object.keys(obj): Returns property names array.

2. Object.values(obj): Returns property values array.

3. Object.entries(obj): Returns [key, value] pairs array.


Example 

javascript
const user = {name: 'Alice', age: 28, city: 'NYC'};

Object.entries(user).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
// name: Alice
// age: 28
// city: NYC


Destructuring: Extract Values Cleanly

Destructuring unpacks object properties into variables, reducing repetitive obj.property access.


Basic Syntax

javascript
const {name, age} = user; // name = 'Alice', age = 28


Advanced Patterns:


1. Rename properties: const {name: fullName} = user;

2. Provide defaults: const {job = 'Developer'} = user;

3. Nested destructuring:

javascript
const person = {name: 'Bob', address: {city: 'LA'}};
const {address: {city}} = person; // city = 'LA'


Function Parameters (huge time-saver)

javascript
function greet({name, age = 25}) {
return `Hello ${name}, age ${age}!`;
}
greet(user); // "Hello Alice, age 28!"

Combining Arrays and Objects: Real Projects

The magic happens when you chain array methods with object destructuring for data pipelines.


Practical Project: User Dashboard Data Prep

Transform raw API data into display-ready format.

javascript
const users = [
{id: 1, name: 'John', orders: [{total: 100}, {total: 50}]},
{id: 2, name: 'Jane', orders: [{total: 200}]}
];

// Calculate total spending per user
const userStats = users.map(({id, name, orders}) => ({
id,
name,
totalSpent: orders.reduce((sum, order) => sum + order.total, 0)
}));

// Filter high-spenders
const highValue = userStats.filter(user => user.totalSpent > 100);
// [{id: 1, name: 'John', totalSpent: 150}, {id: 2, name: 'Jane', totalSpent: 200}]


Step-by-Step Breakdown



Performance Tips for Production


1. Short-circuit early Filter before expensive map/reduce operations.

2. Avoid inline functions in hot loops—extract to named functions.

3. Use for...of for 20-30% faster iteration than map/filter in large datasets.