Popular Searches
Popular Course Categories
Popular Courses

Array Methods: map, filter, find, and reduce

Array Methods: map, filter, find, and reduce

JavaScript and Modern ES6+ Fundamentals

Array Methods: map(), filter(), find(), and reduce() in JavaScript for React Native

Course: React Native Training

Topic: JavaScript Array Methods — map(), filter(), find(), and reduce()

Course Link: React Native Training at JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to JavaScript Array Methods

Arrays are used to store multiple values in a single variable. In JavaScript and React Native, arrays commonly contain user information, product details, messages, orders, categories, API responses, and other collections of data.

JavaScript provides built-in array methods that help developers transform, search, filter, and summarize data without writing repetitive loops. Four especially useful methods are map(), filter(), find(), and reduce().

These methods accept callback functions that define how each array element should be processed. They are widely used in React Native to prepare API data, display lists, search records, calculate shopping-cart totals, and generate summaries.

1.1 What Is an Array?

An array is an ordered collection of values. Each element has an index, starting from zero.

const fruits = ["Apple", "Banana", "Mango"];

console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);

Output:

Apple
Banana
Mango

In this example, fruits[0] accesses the first element, fruits[1] accesses the second element, and fruits[2] accesses the third element.

1.2 Why Are Array Methods Important?

  • Data transformation: Convert values into a different format using map().
  • Data filtering: Select elements that meet a condition using filter().
  • Data searching: Find the first matching element using find().
  • Data aggregation: Calculate totals or combine values using reduce().
  • Readable code: Express common data operations in a concise way.
  • React Native development: Prepare data for lists, product screens, search results, and dashboards.
  • Reusable logic: Pass different callback functions to process data in different ways.

2. Learning Objectives

After completing these notes, learners should be able to:

  • Understand arrays and callback functions.
  • Use map() to transform array elements.
  • Use filter() to select multiple matching elements.
  • Use find() to locate the first matching element.
  • Use reduce() to calculate totals and aggregate data.
  • Understand the differences between the four methods.
  • Work with arrays of objects.
  • Combine multiple array methods through method chaining.
  • Use array methods to render lists in React Native.
  • Filter product and user data based on conditions.
  • Calculate shopping-cart totals and other summaries.
  • Recognize common mistakes and follow best practices.

3. Understanding Callback Functions in Array Methods

A callback function is a function passed to another function as an argument. Array methods use callbacks to determine what should happen to each element.

3.1 Basic Callback Example

const numbers = [10, 20, 30];

numbers.forEach(function (number) {
  console.log(number);
});

Output:

10
20
30

The function passed to forEach() is a callback. The array method calls it for each element.

3.2 Using an Arrow Function as a Callback

const numbers = [10, 20, 30];

numbers.forEach(number => {
  console.log(number);
});

Arrow functions are frequently used with array methods because they provide concise syntax.

3.3 Callback Parameters

For the four methods covered in these notes, the callback can receive up to three commonly used arguments:

Parameter Meaning Example
element The current array element being processed. number
index The index of the current element. index
array The original array on which the method was called. array
const fruits = ["Apple", "Banana", "Mango"];

fruits.map((fruit, index, array) => {
  console.log(fruit, index, array.length);
  return fruit;
});

The callback receives the current fruit, its index, and the array being processed. The callback's return value determines the output behavior of each array method.

4. The map() Method

The map() method creates a new array by calling a callback function for each element in the original array. Each callback return value becomes an element in the new array.

Main purpose: Transform every array element into a corresponding result.

4.1 Syntax of map()

const newArray = array.map((element, index, array) => {
  return transformedValue;
});
  • array: The original array.
  • map(): The method used to transform each element.
  • element: The current item.
  • index: The current item's index, if needed.
  • return: Provides the value to place in the new array.
  • newArray: The resulting array.

4.2 Example: Doubling Numbers

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

const doubledNumbers = numbers.map(number => number * 2);

console.log(doubledNumbers);
console.log(numbers);

Output:

[2, 4, 6, 8, 10]
[1, 2, 3, 4, 5]

The callback multiplies each number by two. The original array remains unchanged because the callback does not modify it.

4.3 Example: Converting Names to Uppercase

const names = ["aarav", "priya", "rohan"];

const uppercaseNames = names.map(name => name.toUpperCase());

console.log(uppercaseNames);

Output:

["AARAV", "PRIYA", "ROHAN"]

4.4 Example: Extracting Values from Objects

Arrays often contain objects instead of simple values. The map() method can extract a property from each object.

const users = [
  { id: 1, name: "Aarav", age: 22 },
  { id: 2, name: "Priya", age: 25 },
  { id: 3, name: "Rohan", age: 28 }
];

const userNames = users.map(user => user.name);

console.log(userNames);

Output:

["Aarav", "Priya", "Rohan"]

4.5 Example: Creating New Objects

You can use map() to create a new array of objects with additional or modified properties.

const products = [
  { id: 1, name: "Phone", price: 15000 },
  { id: 2, name: "Laptop", price: 50000 }
];

const updatedProducts = products.map(product => ({
  ...product,
  priceWithTax: product.price * 1.18
}));

console.log(updatedProducts);

The spread syntax copies the existing properties into a new object, and priceWithTax is added. The original product objects are not modified by this transformation.

4.6 Example: Using the Index

const fruits = ["Apple", "Banana", "Mango"];

const fruitLabels = fruits.map((fruit, index) => {
  return `${index + 1}. ${fruit}`;
});

console.log(fruitLabels);

Output:

["1. Apple", "2. Banana", "3. Mango"]

4.7 When Should You Use map()?

  • When converting prices into formatted values.
  • When extracting names or IDs from objects.
  • When preparing data for display.
  • When transforming API responses.
  • When creating React Native components from array elements.
  • When adding calculated properties to copied objects.

4.8 Common map() Mistake

const numbers = [1, 2, 3];

const result = numbers.map(number => {
  number * 2;
});

console.log(result);

Output:

[undefined, undefined, undefined]

The callback uses curly braces but does not return a value. Correct the code using an explicit return statement or an implicit return.

const result1 = numbers.map(number => {
  return number * 2;
});

const result2 = numbers.map(number => number * 2);

5. The filter() Method

The filter() method creates a new array containing only the elements for which the callback returns a truthy value.

Main purpose: Select multiple elements that satisfy a condition.

5.1 Syntax of filter()

const filteredArray = array.filter((element, index, array) => {
  return condition;
});

If the condition is true, the element is included in the result. If the condition is false, it is excluded.

5.2 Example: Filtering Even Numbers

const numbers = [1, 2, 3, 4, 5, 6, 7, 8];

const evenNumbers = numbers.filter(number => number % 2 === 0);

console.log(evenNumbers);

Output:

[2, 4, 6, 8]

5.3 Example: Filtering Numbers Greater Than a Value

const numbers = [10, 25, 5, 40, 15, 50];

const filteredNumbers = numbers.filter(number => number > 20);

console.log(filteredNumbers);

Output:

[25, 40, 50]

5.4 Example: Filtering Users by Age

const users = [
  { id: 1, name: "Aarav", age: 17 },
  { id: 2, name: "Priya", age: 24 },
  { id: 3, name: "Rohan", age: 30 },
  { id: 4, name: "Neha", age: 16 }
];

const adults = users.filter(user => user.age >= 18);

console.log(adults);

The result contains Priya and Rohan because their ages are at least 18.

5.5 Example: Filtering Products by Price

const products = [
  { id: 1, name: "Phone", price: 15000 },
  { id: 2, name: "Laptop", price: 55000 },
  { id: 3, name: "Headphones", price: 2500 },
  { id: 4, name: "Tablet", price: 22000 }
];

const affordableProducts = products.filter(
  product => product.price < 20000
);

console.log(affordableProducts);

The resulting array contains the Phone and Headphones because their prices are below 20,000.

5.6 Example: Searching Text with filter()

The filter() method can be used to return every item that matches a search query.

const fruits = ["Apple", "Banana", "Grapes", "Mango", "Orange"];

const query = "an";

const matchingFruits = fruits.filter(fruit =>
  fruit.toLowerCase().includes(query.toLowerCase())
);

console.log(matchingFruits);

Output:

["Banana", "Mango", "Orange"]

5.7 What Happens When No Elements Match?

const numbers = [1, 3, 5, 7];

const evenNumbers = numbers.filter(number => number % 2 === 0);

console.log(evenNumbers);

Output:

[]

If no elements satisfy the condition, filter() returns an empty array rather than null or undefined.

5.8 When Should You Use filter()?

  • When displaying only active users.
  • When showing products within a price range.
  • When filtering search results.
  • When selecting completed or pending tasks.
  • When filtering orders by status.
  • When selecting records that meet multiple conditions.

6. The find() Method

The find() method searches an array and returns the first element for which the callback returns a truthy value. It stops searching once it finds a match.

Main purpose: Find a single matching element.

6.1 Syntax of find()

const foundElement = array.find((element, index, array) => {
  return condition;
});

If a matching element exists, the method returns that element. If no element matches, it returns undefined.

6.2 Example: Finding a Number

const numbers = [5, 12, 18, 25, 30];

const foundNumber = numbers.find(number => number > 20);

console.log(foundNumber);

Output:

25

The method returns 25 because it is the first element greater than 20. It does not return 30, even though 30 also satisfies the condition.

6.3 Example: Finding a User by ID

const users = [
  { id: 101, name: "Aarav" },
  { id: 102, name: "Priya" },
  { id: 103, name: "Rohan" }
];

const selectedUser = users.find(user => user.id === 102);

console.log(selectedUser);

Output:

{ id: 102, name: "Priya" }

6.4 Example: Finding a Product

const products = [
  { id: 1, name: "Phone", price: 15000 },
  { id: 2, name: "Laptop", price: 55000 },
  { id: 3, name: "Tablet", price: 22000 }
];

const product = products.find(item => item.name === "Laptop");

console.log(product);

The returned value is the first product object whose name is Laptop.

6.5 Handling an Unsuccessful Search

const users = [
  { id: 1, name: "Aarav" },
  { id: 2, name: "Priya" }
];

const user = users.find(item => item.id === 99);

if (user) {
  console.log(user.name);
} else {
  console.log("User not found");
}

Output:

User not found

Checking the result is important because accessing a property on undefined causes an error.

6.6 When Should You Use find()?

  • When looking up a user by ID.
  • When locating a product by its identifier.
  • When finding a task by its unique ID.
  • When locating a selected category.
  • When retrieving the first record that meets a condition.

7. The reduce() Method

The reduce() method processes array elements and combines them into a single accumulated result. The result may be a number, string, object, array, or another value, depending on the callback.

Main purpose: Accumulate or combine array elements into a final result.

7.1 Syntax of reduce()

const result = array.reduce((accumulator, currentValue, index, array) => {
  return updatedAccumulator;
}, initialValue);
  • accumulator: The value carried from one callback invocation to the next.
  • currentValue: The current element being processed.
  • index: The current element's index, if needed.
  • array: The array being processed.
  • initialValue: The starting value of the accumulator.
  • updatedAccumulator: The value returned by the callback for the next iteration.

7.2 Example: Calculating the Sum

const numbers = [10, 20, 30, 40];

const total = numbers.reduce((sum, number) => {
  return sum + number;
}, 0);

console.log(total);

Output:

100

The accumulator starts at zero. Each number is added to the running total until the array has been processed.

7.3 Understanding Each reduce() Step

For the array [10, 20, 30] and an initial value of zero:

Iteration Accumulator Before Current Value Accumulator After
1 0 10 10
2 10 20 30
3 30 30 60

The final accumulated result is 60.

7.4 Example: Calculating a Shopping Cart Total

const cart = [
  { id: 1, name: "Phone", price: 15000, quantity: 1 },
  { id: 2, name: "Headphones", price: 2000, quantity: 2 },
  { id: 3, name: "Charger", price: 1000, quantity: 3 }
];

const total = cart.reduce((sum, item) => {
  return sum + item.price * item.quantity;
}, 0);

console.log(total);

Output:

21000

The total is calculated by multiplying each item's price by its quantity and adding the resulting amounts.

7.5 Example: Counting Items by Category

const fruits = ["Apple", "Banana", "Apple", "Mango", "Banana", "Apple"];

const counts = fruits.reduce((result, fruit) => {
  result[fruit] = (result[fruit] || 0) + 1;
  return result;
}, {});

console.log(counts);

Output:

{
  Apple: 3,
  Banana: 2,
  Mango: 1
}

The accumulator is an object. Each fruit name becomes a key, and its count is increased whenever that fruit appears.

7.6 Example: Converting an Array into an Object

const users = [
  { id: 1, name: "Aarav" },
  { id: 2, name: "Priya" },
  { id: 3, name: "Rohan" }
];

const usersById = users.reduce((result, user) => {
  result[user.id] = user;
  return result;
}, {});

console.log(usersById[2]);

Output:

{ id: 2, name: "Priya" }

This approach can make records easier to access by ID. If IDs can be arbitrary strings or other values, a JavaScript Map may be a more suitable data structure.

7.7 Example: Calculating an Average

const marks = [80, 90, 70, 100];

const total = marks.reduce((sum, mark) => sum + mark, 0);
const average = marks.length > 0 ? total / marks.length : 0;

console.log(total);
console.log(average);

Output:

340
85

The length check prevents division by zero when the array is empty.

7.8 Why Is an Initial Value Important?

Providing an initial value makes the starting state explicit and allows the callback to process an empty array safely in many common scenarios.

const numbers = [];

const total = numbers.reduce((sum, number) => sum + number, 0);

console.log(total);

Output:

0

Without an initial value, calling reduce() on an empty array throws a TypeError. With an initial value of zero, the result is zero.

7.9 When Should You Use reduce()?

  • When calculating a sum or total.
  • When calculating an average from numeric values.
  • When counting occurrences of items.
  • When grouping data into an object.
  • When calculating shopping-cart totals.
  • When combining array elements into a summary value.

8. Difference Between map(), filter(), find(), and reduce()

Method Primary Purpose Return Value Typical Example
map() Transform every element New array Convert prices to discounted prices
filter() Select all matching elements New array Find all active users
find() Find the first matching element Element or undefined Find a user by ID
reduce() Accumulate values into one result Accumulator result Calculate a cart total

8.1 Same Array, Four Different Methods

const numbers = [10, 20, 30, 40, 50];

// Transform every element.
const doubled = numbers.map(number => number * 2);

// Select every element greater than 25.
const filtered = numbers.filter(number => number > 25);

// Find the first element greater than 25.
const found = numbers.find(number => number > 25);

// Calculate the sum of all elements.
const total = numbers.reduce((sum, number) => sum + number, 0);

console.log(doubled);
console.log(filtered);
console.log(found);
console.log(total);

Output:

[20, 40, 60, 80, 100]
[30, 40, 50]
30
150

8.2 How to Choose the Correct Method

  • Choose map() when you need one transformed result for each input element.
  • Choose filter() when you need all elements that satisfy a condition.
  • Choose find() when you need only the first matching element.
  • Choose reduce() when you need to accumulate data into a summary or other result.

9. Combining Array Methods with Method Chaining

Method chaining means calling one array method after another. It is useful when a data operation involves multiple steps, such as filtering products and then transforming the remaining products.

9.1 Example: Filter and Then Map

const products = [
  { id: 1, name: "Phone", price: 15000 },
  { id: 2, name: "Laptop", price: 55000 },
  { id: 3, name: "Headphones", price: 2000 },
  { id: 4, name: "Tablet", price: 22000 }
];

const affordableProductNames = products
  .filter(product => product.price < 20000)
  .map(product => product.name);

console.log(affordableProductNames);

Output:

["Phone", "Headphones"]

First, filter() selects products below 20,000. Then, map() extracts the names from the filtered products.

9.2 Example: Filter and Then Reduce

const orders = [
  { id: 1, status: "completed", amount: 500 },
  { id: 2, status: "pending", amount: 300 },
  { id: 3, status: "completed", amount: 700 },
  { id: 4, status: "cancelled", amount: 200 }
];

const completedTotal = orders
  .filter(order => order.status === "completed")
  .reduce((sum, order) => sum + order.amount, 0);

console.log(completedTotal);

Output:

1200

The chain selects completed orders and then calculates their combined amount.

9.3 Example: Map and Then Reduce

const prices = [100, 200, 300];

const totalWithTax = prices
  .map(price => price * 1.18)
  .reduce((sum, price) => sum + price, 0);

console.log(totalWithTax);

The first operation calculates a tax-inclusive value for each price. The second adds those values together.

9.4 Example: Find an Item After Filtering

const products = [
  { id: 1, name: "Phone", inStock: true },
  { id: 2, name: "Laptop", inStock: false },
  { id: 3, name: "Tablet", inStock: true }
];

const availableProducts = products.filter(product => product.inStock);
const selectedProduct = availableProducts.find(product => product.name === "Tablet");

console.log(selectedProduct);

In this example, the products are filtered first, and then the first matching Tablet product is selected.

10. Using Array Methods with React Native

React Native applications frequently receive arrays from APIs or store collections in component state. Array methods help transform and display these collections in a mobile interface.

10.1 Rendering a List with map()

import React from "react";
import { View, Text } from "react-native";

export default function FruitList() {
  const fruits = ["Apple", "Banana", "Mango"];

  return (
    <View>
      {fruits.map(fruit => (
        <Text key={fruit}>{fruit}</Text>
      ))}
    </View>
  );
}

The callback passed to map() returns one Text component for each fruit. Each rendered item should have a stable, unique key. In this simple example, each fruit name is used as the key because the values are unique.

10.2 Filtering Products in React Native

import React from "react";
import { View, Text } from "react-native";

const products = [
  { id: "1", name: "Phone", price: 15000 },
  { id: "2", name: "Laptop", price: 55000 },
  { id: "3", name: "Headphones", price: 2000 }
];

export default function AffordableProducts() {
  const affordableProducts = products.filter(
    product => product.price < 20000
  );

  return (
    <View>
      <Text>Affordable Products</Text>
      {affordableProducts.map(product => (
        <Text key={product.id}>
          {product.name}: ₹{product.price}
        </Text>
      ))}
    </View>
  );
}

The screen displays only products priced below 20,000. The product data is filtered before rendering.

10.3 Finding a User by ID

import React from "react";
import { View, Text } from "react-native";

const users = [
  { id: 1, name: "Aarav" },
  { id: 2, name: "Priya" },
  { id: 3, name: "Rohan" }
];

export default function UserDetails() {
  const selectedUser = users.find(user => user.id === 2);

  return (
    <View>
      {selectedUser ? (
        <Text>Selected User: {selectedUser.name}</Text>
      ) : (
        <Text>User not found</Text>
      )}
    </View>
  );
}

The component uses find() to retrieve the user with ID 2. It checks whether a match exists before accessing the user's name.

10.4 Calculating a Total with reduce()

import React from "react";
import { View, Text } from "react-native";

export default function CartSummary() {
  const cart = [
    { id: "1", name: "Phone", price: 15000, quantity: 1 },
    { id: "2", name: "Headphones", price: 2000, quantity: 2 }
  ];

  const total = cart.reduce((sum, item) => {
    return sum + item.price * item.quantity;
  }, 0);

  return (
    <View>
      <Text>Shopping Cart Summary</Text>
      <Text>Total: ₹{total}</Text>
    </View>
  );
}

The total is 19,000. The reduce() callback multiplies each item's price by its quantity and adds the result to the accumulator.

11. Working with API Data

React Native applications often retrieve lists from web APIs. Once the response has been parsed, array methods can help prepare the information for display.

11.1 Example: Transforming API Data

async function loadUsers() {
  const response = await fetch("https://jsonplaceholder.typicode.com/users");

  if (!response.ok) {
    throw new Error("Failed to load users");
  }

  const users = await response.json();

  return users.map(user => ({
    id: user.id,
    name: user.name,
    email: user.email
  }));
}

The map() method returns a new array containing only the selected properties from each API user object.

11.2 Example: Filtering API Results

const matchingUsers = users.filter(user =>
  user.name.toLowerCase().includes("a")
);

This returns users whose names contain the letter “a”, without regard to case.

11.3 Example: Finding a Specific API Record

const selectedUser = users.find(user => user.id === 5);

if (selectedUser) {
  console.log(selectedUser.email);
} else {
  console.log("No matching user found");
}

11.4 Example: Summarizing API Results

const totalPosts = posts.reduce((count, post) => {
  return count + 1;
}, 0);

console.log(totalPosts);

This example counts the elements in the posts array. In ordinary code, posts.length is simpler for this particular task, but reduce() is useful when a count depends on more complex conditions.

12. Common Mistakes and How to Avoid Them

12.1 Using map() When filter() Is Needed

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

// This transforms values into booleans.
const incorrect = numbers.map(number => number > 3);

// This returns only matching numbers.
const correct = numbers.filter(number => number > 3);

map() returns one result for each processed element, while filter() selects the original elements that satisfy the condition.

12.2 Expecting find() to Return Every Match

const numbers = [10, 20, 30, 40];

const result = numbers.find(number => number > 15);

console.log(result);

The result is 20, not an array of every matching number. Use filter() if all matches are needed.

12.3 Forgetting the Return Statement in reduce()

const numbers = [1, 2, 3];

const total = numbers.reduce((sum, number) => {
  sum + number;
}, 0);

console.log(total);

The callback does not return the updated accumulator, so the next iteration receives undefined and the calculation fails. Use:

const total = numbers.reduce((sum, number) => {
  return sum + number;
}, 0);

12.4 Forgetting the Initial Value in reduce()

const numbers = [];

const total = numbers.reduce((sum, number) => sum + number, 0);

console.log(total); // 0

For numeric totals, supplying zero as the initial accumulator makes the intended behavior clear and handles empty arrays safely.

12.5 Accessing Properties of an Undefined Result

const users = [{ id: 1, name: "Aarav" }];

const user = users.find(item => item.id === 2);

// Check whether a matching user exists.
if (user) {
  console.log(user.name);
} else {
  console.log("User not found");
}

Always account for the possibility that find() returns undefined.

12.6 Modifying Original Objects Unintentionally

// Avoid changing the existing objects when a new result is intended.
const updatedUsers = users.map(user => ({
  ...user,
  active: true
}));

Array methods such as map() and filter() create new arrays, but they do not automatically deep-copy objects inside those arrays. Use object copying when you need updated objects without modifying the original ones.

12.7 Using map() Only for Side Effects

// Prefer forEach() when no transformed array is needed.
users.forEach(user => {
  console.log(user.name);
});

If you do not use the array returned by map(), consider whether forEach() or a loop better expresses your intention.

13. Performance and Best Practices

  • Use the method whose return value matches the task.
  • Keep callback functions easy to read and understand.
  • Use map() for transformations rather than filtering or side effects.
  • Use filter() when you need every element that matches a condition.
  • Use find() when only the first match is required.
  • Use reduce() for meaningful aggregation instead of making simple operations unnecessarily complicated.
  • Provide an initial value to reduce() when appropriate, especially for numeric totals.
  • Use stable and unique keys when rendering arrays of React Native elements.
  • Avoid mutating state arrays and objects directly.
  • Consider the cost of chaining methods on very large arrays, because each method may traverse data and create intermediate arrays.
  • Do not assume find() or filter() returns a particular element without checking the condition.
  • Use clear variable names such as activeUsers, selectedProduct, and cartTotal.
  • Test empty arrays, missing values, duplicate matches, and boundary conditions.

14. Practical Exercise 1: Number Transformation

Objective: Use map() to create a new array containing the squares of numbers.

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

const squares = numbers.map(number => number * number);

console.log(squares);

Expected output:

[4, 9, 16, 25]

Practice task: Create a second array containing the cubes of the same numbers.

15. Practical Exercise 2: Filter Eligible Users

Objective: Select users whose age is at least 18.

const users = [
  { id: 1, name: "Aarav", age: 17 },
  { id: 2, name: "Priya", age: 24 },
  { id: 3, name: "Rohan", age: 19 },
  { id: 4, name: "Neha", age: 16 }
];

const eligibleUsers = users.filter(user => user.age >= 18);

console.log(eligibleUsers);

Expected result: The array contains Priya and Rohan.

Practice task: Filter users whose age is between 18 and 25, inclusive.

16. Practical Exercise 3: Find a Product

Objective: Find the first product that matches a specific ID.

const products = [
  { id: 101, name: "Phone", price: 15000 },
  { id: 102, name: "Laptop", price: 55000 },
  { id: 103, name: "Tablet", price: 22000 }
];

const selectedProduct = products.find(product => product.id === 102);

console.log(selectedProduct);

Expected result: The Laptop object is returned.

Practice task: Search for a product ID that does not exist and display a suitable message.

17. Practical Exercise 4: Calculate Shopping Cart Total

Objective: Use reduce() to calculate the total cost of a shopping cart.

const cart = [
  { name: "Notebook", price: 100, quantity: 3 },
  { name: "Pen", price: 20, quantity: 5 },
  { name: "Bag", price: 800, quantity: 1 }
];

const total = cart.reduce((sum, item) => {
  return sum + item.price * item.quantity;
}, 0);

console.log(total);

Expected output:

1200

Practice task: Calculate the total number of items in the cart and the average price per product line.

18. Mini Project: React Native Product List

Project objective: Create a simple product screen that uses filter(), map(), find(), and reduce() to prepare and display product information.

18.1 Project Features

  • Display a list of products.
  • Filter products based on their price.
  • Find a product by its ID.
  • Calculate the combined price of the products.
  • Render product information using React Native components.

18.2 Example Implementation

import React from "react";
import { View, Text, FlatList, StyleSheet } from "react-native";

const products = [
  { id: "1", name: "Phone", price: 15000 },
  { id: "2", name: "Laptop", price: 55000 },
  { id: "3", name: "Headphones", price: 2000 },
  { id: "4", name: "Tablet", price: 22000 }
];

export default function ProductScreen() {
  const affordableProducts = products.filter(
    product => product.price < 20000
  );

  const selectedProduct = products.find(
    product => product.id === "2"
  );

  const totalPrice = products.reduce(
    (sum, product) => sum + product.price,
    0
  );

  const productNames = products.map(product => product.name);

  return (
    <View style={styles.container}>
      <Text style={styles.heading}>Product List</Text>

      <Text>All Products: {productNames.join(", ")}</Text>

      <Text style={styles.subheading}>Affordable Products</Text>
      {affordableProducts.map(product => (
        <Text key={product.id}>
          {product.name} - ₹{product.price}
        </Text>
      ))}

      <Text style={styles.subheading}>Selected Product</Text>
      {selectedProduct ? (
        <Text>
          {selectedProduct.name} - ₹{selectedProduct.price}
        </Text>
      ) : (
        <Text>Product not found</Text>
      )}

      <Text style={styles.total}>Combined Price: ₹{totalPrice}</Text>

      <Text style={styles.subheading}>All Product Records</Text>
      <FlatList
        data={products}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <Text>{item.name}: ₹{item.price}</Text>
        )}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20
  },
  heading: {
    fontSize: 24,
    fontWeight: "bold",
    marginBottom: 12
  },
  subheading: {
    fontSize: 18,
    fontWeight: "bold",
    marginTop: 16
  },
  total: {
    fontSize: 18,
    fontWeight: "bold",
    marginTop: 20
  }
});

18.3 Concepts Practised

  • map() creates an array of product names.
  • filter() selects products below the price limit.
  • find() retrieves the first product matching the specified ID.
  • reduce() calculates the combined price.
  • FlatList renders product records with stable keys.

19. Interview Questions and Answers

Q1. What is map() in JavaScript?

map() creates a new array by calling a callback for each element and placing each callback's return value into the resulting array.

Q2. Does map() modify the original array?

The method itself does not modify the original array. However, if the callback mutates objects referenced by the original array, those object mutations can still affect the original data.

Q3. What is filter() used for?

filter() creates a new array containing the elements for which the callback returns a truthy value.

Q4. What is the difference between filter() and find()?

filter() returns a new array containing all matching elements. find() returns the first matching element or undefined if no match exists.

Q5. What does reduce() do?

reduce() processes the array using an accumulator and returns the final accumulated result.

Q6. Why is an initial value useful in reduce()?

An initial value defines the starting accumulator and allows empty arrays to be handled safely for operations such as summing numbers.

Q7. Can map() return objects?

Yes. The callback can return any value, including objects, arrays, strings, numbers, or React elements.

Q8. What happens when find() does not locate an element?

It returns undefined. Code should check the result before accessing its properties.

Q9. Can these methods be chained?

Yes. For example, filter() can select records and map() can transform those records. reduce() can then calculate a summary from the selected values.

Q10. How are array methods used in React Native?

They are used to transform API data, filter records, find individual objects, calculate totals, and prepare lists for rendering.

Q11. What is the difference between map() and forEach()?

map() returns a new array of callback results. forEach() executes a callback for each element and returns undefined.

Q12. Does find() examine every element?

Not necessarily. It stops once the first matching element is found.

Q13. What does filter() return when there are no matches?

It returns an empty array.

Q14. What is the accumulator in reduce()?

The accumulator stores the intermediate result that is passed from one callback invocation to the next.

Q15. Why are array methods useful in mobile application development?

They make it easier to prepare and process collections of application data with concise, reusable logic.

20. Quick Revision Checklist

  • Understand arrays, indexes, and callback functions.
  • Use map() to transform every element into a corresponding result.
  • Use filter() to select every element that satisfies a condition.
  • Use find() to locate the first matching element.
  • Use reduce() to accumulate values into a final result.
  • Remember that find() returns undefined if there is no match.
  • Provide an initial value to reduce() when appropriate.
  • Understand the difference between transforming, filtering, searching, and aggregating.
  • Practise chaining multiple array methods.
  • Use array methods to prepare React Native lists and API responses.
  • Avoid unintended mutation of objects and arrays.
  • Use stable keys when rendering arrays of React elements.

21. Recommended Learning Resources

22. Conclusion

The JavaScript array methods map(), filter(), find(), and reduce() are essential tools for handling collections of data. Each method serves a distinct purpose: map() transforms elements, filter() selects matching elements, find() returns the first matching element, and reduce() combines elements into an accumulated result.

In React Native, these methods help developers display lists, process API responses, search for records, filter products, and calculate totals. Practising the examples and mini project will help learners write cleaner, more readable, and maintainable JavaScript code.

To learn more about mobile application development, visit React Native Training at JustAcademy or use the course demo registration link.

whatsapp