Mastering JavaScript: Mapping, Reducing, and Filtering Free PDF Quiz and Exercise to learn and practice JavaScript

Mastering JavaScript: Mapping, Reducing, and Filtering

Mapping the values of an array in JavaScript is a powerful technique that involves applying a function to each element of an array, creating a new array with the results. Let’s dive into a detailed explanation with coding examples:

Understanding Array Mapping:

1. Introduction:

Mapping is a fundamental operation in JavaScript that transforms each element of an array based on a provided function, creating a new array with the transformed values. It’s a concise and expressive way to modify array elements without modifying the original array.

2. Syntax:

The map method is used for array mapping. Here’s the basic syntax:

const newArray = originalArray.map(callbackFunction);

3. Callback Function:

The callbackFunction is applied to each element of the array. It takes three arguments: currentValue, index, and array. You can use any of these based on your mapping logic.

Coding Examples for Mapping

Example 1: Doubling Numbers

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

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

console.log(doubledNumbers);

// Output: [2, 4, 6, 8, 10]

Example 2: Uppercasing Strings

const words = [‘apple’, ‘banana’, ‘cherry’];

const uppercasedWords = words.map((word) => word.toUpperCase());

console.log(uppercasedWords);

// Output: [‘APPLE’, ‘BANANA’, ‘CHERRY’]

Example 3: Extracting Object Properties

const users = [

  { name: ‘Alice’, age: 25 },

  { name: ‘Bob’, age: 30 },

  { name: ‘Charlie’, age: 22 }

];

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

console.log(names);

// Output: [‘Alice’, ‘Bob’, ‘Charlie’]

Example 4: Calculating Square Roots

const numbers = [4, 9, 16, 25];

const squareRoots = numbers.map((number) => Math.sqrt(number));

console.log(squareRoots);

// Output: [2, 3, 4, 5]

Example 5: Custom Mapping Function

const temperaturesInCelsius = [25, 30, 15, 20];

const temperaturesInFahrenheit = temperaturesInCelsius.map((celsius) => {

  // Custom mapping function

  return (celsius * 9/5) + 32;

});

console.log(temperaturesInFahrenheit);

// Output: [77, 86, 59, 68]

Key Takeaways:

Use the map method for transforming array elements based on a provided function.

The callback function can be customized according to the transformation logic needed.

Mapping creates a new array, leaving the original array unchanged.

Mapping is a versatile tool in JavaScript, allowing you to efficiently transform and derive new arrays from existing ones. Practice using it with various scenarios to strengthen your understanding. 

10 coding exercises 

Here are 10 coding exercises to enhance your skills in mapping values of arrays in JavaScript. Each exercise includes steps, descriptions, code examples, and solutions.

Exercise 1: Double the Numbers

Task: Given an array of numbers, create a new array with each number doubled.

Steps:

  1. Declare an array of numbers.
  2. Use the map method to create a new array where each number is doubled.

Code:

const originalNumbers = [2, 4, 6, 8, 10];

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

console.log(doubledNumbers);

// Output: [4, 8, 12, 16, 20]

Exercise 2: Uppercase Strings

Task: Given an array of strings, create a new array with each string converted to uppercase.

Steps:

  1. Declare an array of strings.
  2. Use the map method to create a new array with uppercase strings.

Code:

const originalWords = [‘apple’, ‘banana’, ‘cherry’];

const uppercasedWords = originalWords.map((word) => word.toUpperCase());

console.log(uppercasedWords);

// Output: [‘APPLE’, ‘BANANA’, ‘CHERRY’]

Exercise 3: Extract Object Properties

Task: Given an array of objects, create a new array with values extracted from a specific property.

Steps:

  1. Declare an array of objects.
  2. Use the map method to create a new array with values extracted from a specific property.

Code:

const users = [

  { name: ‘Alice’, age: 25 },

  { name: ‘Bob’, age: 30 },

  { name: ‘Charlie’, age: 22 }

];

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

console.log(names);

// Output: [‘Alice’, ‘Bob’, ‘Charlie’]

Exercise 4: Calculate Square Roots

Task: Given an array of numbers, create a new array with the square root of each number.

Steps:

  1. Declare an array of numbers.
  2. Use the map method to create a new array with the square root of each number.

Code:

const originalNumbers = [4, 9, 16, 25];

const squareRoots = originalNumbers.map((number) => Math.sqrt(number));

console.log(squareRoots);

// Output: [2, 3, 4, 5]

Exercise 5: Customize Mapping Function

Task: Given an array of temperatures in Celsius, create a new array with temperatures converted to Fahrenheit.

Steps:

  1. Declare an array of temperatures in Celsius.
  2. Use the map method with a custom mapping function to convert temperatures to Fahrenheit.

Code:

const temperaturesInCelsius = [25, 30, 15, 20];

const temperaturesInFahrenheit = temperaturesInCelsius.map((celsius) => (celsius * 9/5) + 32);

console.log(temperaturesInFahrenheit);

// Output: [77, 86, 59, 68]

Exercise 6: Square Even Numbers

Task: Given an array of numbers, create a new array with only the square of even numbers.

Steps:

  1. Declare an array of numbers.
  2. Use the map method with a conditional statement to filter and square even numbers.

Code:

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

const squaresOfEvens = originalNumbers.map((number) => (number % 2 === 0) ? number * number : number);

console.log(squaresOfEvens);

// Output: [1, 4, 3, 16, 5]

Exercise 7: Calculate Area of Rectangles

Task: Given an array of rectangles with width and height, create a new array with the calculated area of each rectangle.

Steps:

  1. Declare an array of rectangles (objects with width and height).
  2. Use the map method to create a new array with the calculated area for each rectangle.

Code:

const rectangles = [

  { width: 3, height: 5 },

  { width: 4, height: 8 },

  { width: 2, height: 6 }

];

const areas = rectangles.map((rectangle) => rectangle.width * rectangle.height);

console.log(areas);

// Output: [15, 32, 12]

Exercise 8: Extract Initials from Names

Task: Given an array of names, create a new array with the initials of each name.

Steps:

  1. Declare an array of names.
  2. Use the map method to create a new array with the initials of each name.

Code:

const names = [‘John Doe’, ‘Alice Smith’, ‘Bob Johnson’];

const initials = names.map((name) => {

  const [firstName, lastName] = name.split(‘ ‘);

  return `${firstName.charAt(0)}${lastName.charAt(0)}`;

});

console.log(initials);

// Output: [‘JD’, ‘AS’, ‘BJ’]

Exercise 9: Format Dates

Task: Given an array of date strings, create a new array with formatted dates.

Steps:

  1. Declare an array of date strings.
  2. Use the map method with a date formatting function to create a new array with formatted dates.

Code:

const dateStrings = [‘2023-01-15’, ‘2023-05-20’, ‘2023-09-10’];

const formattedDates = dateStrings.map((dateString) => {

  const date = new Date(dateString);

  return `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`;

});

console.log(formattedDates);

// Output: [‘1/15/2023’, ‘5/20/2023’, ‘9/10/2023’]

Exercise 10: Create HTML List

Task: Given an array of items, create an HTML list using the map method.

Steps:

  1. Declare an array of items.
  2. Use the map method to create an HTML list string.

Code:

const items = [‘Apple’, ‘Banana’, ‘Cherry’, ‘Date’];

const htmlList = `<ul>${items.map((item) => `<li>${item}</li>`).join(”)}</ul>`;

console.log(htmlList);

// Output: ‘<ul><li>Apple</li><li>Banana</li><li>Cherry</li><li>Date</li></ul>’

Solutions to exercises:

Exercise 1: Double the Numbers

const originalNumbers = [2, 4, 6, 8, 10];

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

console.log(doubledNumbers);

// Output: [4, 8, 12, 16, 20]

Exercise 2: Uppercase Strings

const originalWords = [‘apple’, ‘banana’, ‘cherry’];

const uppercasedWords = originalWords.map((word) => word.toUpperCase());

console.log(uppercasedWords);

// Output: [‘APPLE’, ‘BANANA’, ‘CHERRY’]

Exercise 3: Extract Object Properties

const users = [

  { name: ‘Alice’, age: 25 },

  { name: ‘Bob’, age: 30 },

  { name: ‘Charlie’, age: 22 }

];

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

console.log(names);

// Output: [‘Alice’, ‘Bob’, ‘Charlie’]

Exercise 4: Calculate Square Roots

const originalNumbers = [4, 9, 16, 25];

const squareRoots = originalNumbers.map((number) => Math.sqrt(number));

console.log(squareRoots);

// Output: [2, 3, 4, 5]

Exercise 5: Customize Mapping Function

const temperaturesInCelsius = [25, 30, 15, 20];

const temperaturesInFahrenheit = temperaturesInCelsius.map((celsius) => (celsius * 9/5) + 32);

console.log(temperaturesInFahrenheit);

// Output: [77, 86, 59, 68]

Exercise 6: Square Even Numbers

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

const squaresOfEvens = originalNumbers.map((number) => (number % 2 === 0) ? number * number : number);

console.log(squaresOfEvens);

// Output: [1, 4, 3, 16, 5]

Exercise 7: Calculate Area of Rectangles

const rectangles = [

  { width: 3, height: 5 },

  { width: 4, height: 8 },

  { width: 2, height: 6 }

];

const areas = rectangles.map((rectangle) => rectangle.width * rectangle.height);

console.log(areas);

// Output: [15, 32, 12]

Exercise 8: Extract Initials from Names

const names = [‘John Doe’, ‘Alice Smith’, ‘Bob Johnson’];

const initials = names.map((name) => {

  const [firstName, lastName] = name.split(‘ ‘);

  return `${firstName.charAt(0)}${lastName.charAt(0)}`;

});

console.log(initials);

// Output: [‘JD’, ‘AS’, ‘BJ’]

Exercise 9: Format Dates

const dateStrings = [‘2023-01-15’, ‘2023-05-20’, ‘2023-09-10’];

const formattedDates = dateStrings.map((dateString) => {

  const date = new Date(dateString);

  return `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`;

});

console.log(formattedDates);

// Output: [‘1/15/2023’, ‘5/20/2023’, ‘9/10/2023’]

Exercise 10: Create HTML List

const items = [‘Apple’, ‘Banana’, ‘Cherry’, ‘Date’];

const htmlList = `<ul>${items.map((item) => `<li>${item}</li>`).join(”)}</ul>`;

console.log(htmlList);

// Output: ‘<ul><li>Apple</li><li>Banana</li><li>Cherry</li><li>Date</li></ul>’

Quiz Questions:

Question: What is the purpose of the map method in JavaScript?

A) To filter elements in an array.

B) To modify elements in an array based on a function.

C) To create a new array with specified elements.

D) To check if a specific element exists in an array.

Question: In JavaScript mapping, what does the callback function receive as its arguments?

A) Current index only.

B) Current element only.

C) Both current element and index.

D) Current element, index, and array.

Question: How do you double each number in an array using the map method?

A) array.map((num) => num * 2);

B) array.map((num) => num + 2);

C) array.map((num) => num / 2);

D) array.map((num) => num – 2);

Question: What is the result of mapping uppercase strings from [‘apple’, ‘banana’]?

A) [‘APPLE’, ‘BANANA’]

B) [‘Apple’, ‘Banana’]

C) [‘apple’, ‘banana’]

D) [‘Apple’, ‘banana’]

Question: Which array method is used to extract specific properties from objects?

A) filter

B) reduce

C) map

D) forEach

Question: How would you extract names from an array of objects: [{ name: ‘Alice’ }, { name: ‘Bob’ }]?

A) array.map((obj) => obj);

B) array.map((name) => name);

C) array.map((obj) => obj.name);

D) array.map((name) => name.name);

Question: What does the following code do: array.map((num) => Math.sqrt(num));?

A) Calculates the square of each number.

B) Calculates the square root of each number.

C) Doubles each number.

D) Adds 10 to each number.

Question: To convert temperatures from Celsius to Fahrenheit, what mapping function would you use?

A) array.map((temp) => temp * 2);

B) array.map((temp) => temp + 32);

C) array.map((temp) => (temp * 9/5) + 32);

D) array.map((temp) => temp / 2);

Question: How do you square only even numbers in an array using map?

A) array.map((num) => num * num);

B) array.map((num) => (num % 2 === 0) ? num * num : num);

C) array.map((num) => (num % 2 === 0) ? num : num * num);

D) array.map((num) => num + 2);

Question: What is the result of the mapping function on [2, 4, 6]: array.map((num) => num + 1);?

A) [2, 4, 6]

B) [3, 5, 7]

C) [1, 3, 5]

D) [4, 6, 8]

Question: In the context of mapping, what does IIFE stand for?

A) Inline Immediate Function Execution

B) Instant Invocation of Function Expression

C) Immediately Invoked Function Expression

D) Inline Instant Function Execution

Question: How would you use map to create an HTML list from [‘Apple’, ‘Banana’]?

A) array.map((item) => `<ul>${item}</ul>`);

B) array.map((item) => `<li>${item}</li>`).join(”);

C) array.map((item) => `<div>${item}</div>`);

D) array.map((item) => `<p>${item}</p>`).concat();

Question: What is the purpose of the join method in JavaScript?

A) To concatenate arrays.

B) To join array elements into a string.

C) To remove elements from an array.

D) To reverse the order of array elements.

Question: How would you create an array of squared numbers using the map method?

A) array.map((num) => num * num);

B) array.map((num) => num + num);

C) array.map((num) => num / num);

D) array.map((num) => num – num);

Question: What happens if you don’t provide a callback function to the map method?

A) The original array is modified.

B) An error is thrown.

C) A new array with the same elements is created.

D) The map method does nothing.

Question: How do you extract the day from an array of date strings using map?

A) array.map((date) => date.getDay());

B) array.map((date) => date.split(‘-‘)[2]);

C) array.map((date) => new Date(date).getDay());

D) array.map((date) => new Date(date).getDate());

Question: What is the result of mapping the initials from [‘John Doe’, ‘Alice Smith’]?

A) [‘JD’, ‘AS’]

B) [‘J’, ‘A’]

C) [‘John’, ‘Alice’]

D) [‘Doe’, ‘Smith’]

Question: How would you filter and map only even numbers from an array?

A) array.map((num) => (num % 2 === 0) ? num : null);

B) array.filter((num) => num % 2 === 0).map((num) => num);

C) array.filter((num) => num % 2 === 0).map((num) => num * num);

D) array.map((num) => num * num).filter((num) => num % 2 === 0);

Question: How do you calculate the total area of rectangles from an array of objects?

A) array.map((rect) => rect.width * rect.height).reduce((acc, area) => acc + area);

B) array.reduce((acc, rect) => acc + (rect.width * rect.height), 0);

C) array.map((rect) => rect.width * rect.height).sum();

D) array.reduce((rect) => rect.width * rect.height).map((area) => area);

Question: What does the following code do: array.map((str) => str.length);?

A) Returns the length of each string in the array.

B) Doubles the length of each string in the array.

C) Concatenates the strings in the array.

D) Returns the average length of the strings in the array.

Question: How do you create an array of formatted dates from an array of date strings?

A) array.map((date) => new Date(date).format(‘MM/DD/YYYY’));

B) array.map((date) => new Date(date).toLocaleDateString());

C) array.map((date) => date.toDateString());

D) array.map((date) => date.format(‘YYYY/MM/DD’));

Question: What is the purpose of the concat method in JavaScript?

A) To concatenate two arrays.

B) To merge objects.

C) To create a shallow copy of an array.

D) To add elements to the beginning of an array.

Question: How do you convert an array of numbers to strings using map?

A) array.map((num) => String(num));

B) array.map((num) => num.toString());

C) array.map((num) => num + ”);

D) array.map((num) => ” + num);

Question: What is the result of mapping a function on [1, 2, 3]: array.map(() => ‘Hello’);?

A) [‘Hello’, ‘Hello’, ‘Hello’]

B) [1, 2, 3]

C) [‘Hello’]

D) []

Question: How would you calculate the sum of squares of numbers in an array using map?

A) array.map((num) => num * num).reduce((acc, square) => acc + square, 0);

B) array.reduce((acc, num) => acc + (num * num), 0);

C) array.map((num) => num * num).sum();

D) array.map((num) => num * num).concat();

Question: What is the purpose of the reduce method in JavaScript?

A) To filter elements in an array.

B) To modify elements in an array based on a function.

C) To create a new array with specified elements.

D) To perform a cumulative operation on elements in an array.

Question: How do you find the maximum number in an array using reduce?

A) array.reduce((max, num) => num > max ? num : max, 0);

B) array.reduce((max, num) => max > num ? max : num, 0);

C) array.reduce((max, num) => num > max ? max : num, Infinity);

D) array.reduce((max, num) => max > num ? max : num, -Infinity);

Question: What is the result of reducing [1, 2, 3] with array.reduce((acc, num) => acc + num, 0);?

A) 1

B) 6

C) 0

D) [1, 2, 3]

Question: How do you concatenate strings in an array using reduce?

A) array.reduce((concatenated, str) => concatenated + str, ”);

B) array.reduce((concatenated, str) => str + concatenated, ”);

C) array.reduce((concatenated, str) => concatenated.concat(str), ”);

D) array.reduce((concatenated, str) => str.concat(concatenated), ”);

Question: What does the forEach method do in JavaScript?

A) Creates a new array with specified elements.

B) Modifies elements in an array based on a function.

C) Executes a provided function once for each array element.

D) Filters elements in an array.

Question: How do you find if all numbers in an array are even using every?

A) array.every((num) => num % 2 === 0);

B) array.every((num) => num % 2 !== 0);

C) array.every((num) => num * 2 === 0);

D) array.every((num) => num / 2 === 0);

Question: What is the purpose of the some method in JavaScript?

A) To check if some elements in an array pass a test.

B) To modify elements in an array based on a function.

C) To create a new array with specified elements.

D) To concatenate two arrays.

Question: How do you check if any string in an array has a length greater than 5 using some?

A) array.some((str) => str.length > 5);

B) array.some((str) => str.length === 5);

C) array.some((str) => str.length < 5);

D) array.some((str) => str.length >= 5);

Question: What is the result of applying filter on [1, 2, 3, 4, 5] with array.filter((num) => num % 2 === 0);?

A) [2, 4]

B) [1, 3, 5]

C) [2, 4, 6]

D) [1, 2, 3, 4, 5]

Question: How do you filter out strings shorter than 3 characters from an array?

A) array.filter((str) => str.length >= 3);

B) array.filter((str) => str.length === 3);

C) “`array.filter((str) => str.length <

D) array.filter((str) => str.length = 3);

Answers to Quiz Questions

Question: What is the purpose of the map method in JavaScript?

C) To create a new array with specified elements.

Question: In JavaScript mapping, what does the callback function receive as its arguments?

C) Both current element and index.

Question: How do you double each number in an array using the map method?

A) array.map((num) => num * 2);

Question: What is the result of mapping uppercase strings from [‘apple’, ‘banana’]?

A) [‘APPLE’, ‘BANANA’]

Question: Which array method is used to extract specific properties from objects?

C) map

Question: How would you extract names from an array of objects: [{ name: ‘Alice’ }, { name: ‘Bob’ }]?

C) array.map((obj) => obj.name);

Question: What does the following code do: array.map((num) => Math.sqrt(num));?

B) Calculates the square root of each number.

Question: To convert temperatures from Celsius to Fahrenheit, what mapping function would you use?

C) array.map((temp) => (temp * 9/5) + 32);

Question: How do you square only even numbers in an array using map?

B) array.map((num) => (num % 2 === 0) ? num * num : num);

Question: What is the result of the mapping function on [2, 4, 6]: array.map((num) => num + 1);?

B) [3, 5, 7]

Question: In the context of mapping, what does IIFE stand for?

C) Immediately Invoked Function Expression

Question: How would you use map to create an HTML list from [‘Apple’, ‘Banana’]?

B) array.map((item) => <li>${item}</li>).join(”);

Question: What is the purpose of the join method in JavaScript?

B) To join array elements into a string.

Question: How would you create an array of squared numbers using the map method?

A) array.map((num) => num * num);

Question: What happens if you don’t provide a callback function to the map method?

C) A new array with the same elements is created.

Question: How do you extract the day from an array of date strings using map?

C) array.map((date) => new Date(date).getDay());

Question: What is the result of mapping the initials from [‘John Doe’, ‘Alice Smith’]?

A) [‘JD’, ‘AS’]

Question: How would you filter and map only even numbers from an array?

B) array.filter((num) => num % 2 === 0).map((num) => num);

Question: How do you calculate the total area of rectangles from an array of objects?

B) array.reduce((acc, rect) => acc + (rect.width * rect.height), 0);

Question: What does the following code do: array.map((str) => str.length);?

A) Returns the length of each string in the array.

Question: How do you create an array of formatted dates from an array of date strings?

B) array.map((date) => new Date(date).toLocaleDateString());

Question: What is the purpose of the concat method in JavaScript?

A) To concatenate two arrays.

Question: How do you convert an array of numbers to strings using map?

A) array.map((num) => String(num));

Question: What is the result of mapping a function on [1, 2, 3]: array.map(() => ‘Hello’);?

A) [‘Hello’, ‘Hello’, ‘Hello’]

Question: How would you calculate the sum of squares of numbers in an array using map?

A) array.map((num) => num * num).reduce((acc, square) => acc + square, 0);

Question: What is the purpose of the reduce method in JavaScript?

D) To perform a cumulative operation on elements in an array.

Question: How do you find the maximum number in an array using reduce?

C) array.reduce((max, num) => num > max ? max : num, Infinity);

Question: What is the result of reducing [1, 2, 3] with array.reduce((acc, num) => acc + num, 0);?

B) 6

Question: How do you concatenate strings in an array using reduce?

A) array.reduce((concatenated, str) => concatenated + str, ”);

Question: What does the forEach method do in JavaScript?

C) Executes a provided function once for each array element.

Question: How do you find if all numbers in an array are even using every?

A) array.every((num) => num % 2 === 0);

Question: What is the purpose of the some method in JavaScript?

A) To check if some elements in an array pass a test.

Question: How do you check if any string in an array has a length greater than 5 using some?

A) array.some((str) => str.length > 5);

Question: What is the result of applying filter on [1, 2, 3, 4, 5] with array.filter((num) => num % 2 === 0);?

A) [2, 4]

Question: How do you filter out strings shorter than 3 characters from an array?

A) array.filter((str) => str.length >= 3);