🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
In JavaScript, you can reduce an array to a single value using the reduce() method. This method applies a function to each element of the array, combining them into a single value, such as a sum, product, or concatenated string. It's a powerful tool for tasks like summing numbers, finding the maximum value, or aggregating data.
Problem Statement
Create a JavaScript program that:
- Accepts an array of elements.
- Reduces the array to a single value based on a specific operation (e.g., sum, product, concatenation).
- Returns and displays the result.
Example:
Input:
[1, 2, 3, 4, 5](sum all the numbers)Output:
15Input:
["a", "b", "c", "d"](concatenate the strings)Output:
"abcd"
Solution Steps
- Read the Input Array: Provide an array of elements either as user input or directly in the code.
- Use the
reduce()Method: Apply thereduce()method to the array, specifying the operation to perform (e.g., summing, concatenating). - Display the Result: Print the reduced value.
JavaScript Program
Example 1: Sum All Numbers in an Array
// JavaScript Program to Sum All Numbers in an Array
// Author: https://www.javaguides.net/
function sumArray(arr) {
// Step 1: Use reduce() to sum all the numbers
return arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
}
// Example input
let numbers = [1, 2, 3, 4, 5];
let sum = sumArray(numbers);
console.log(`The sum of the array is: ${sum}`);
Output
The sum of the array is: 15
Example 2: Concatenate Strings in an Array
// JavaScript Program to Concatenate Strings in an Array
// Author: https://www.javaguides.net/
function concatenateArray(arr) {
// Step 1: Use reduce() to concatenate all the strings
return arr.reduce((accumulator, currentValue) => accumulator + currentValue, '');
}
// Example input
let strings = ["a", "b", "c", "d"];
let concatenatedString = concatenateArray(strings);
console.log(`The concatenated string is: "${concatenatedString}"`);
Output
The concatenated string is: "abcd"
Explanation
Step 1: Use the reduce() Method
- The
reduce()method executes a callback function on each element of the array, resulting in a single output value.- In the first example, the callback function adds each number to an accumulator, which starts at
0. - In the second example, the callback function concatenates each string to an accumulator, which starts as an empty string (
'').
- In the first example, the callback function adds each number to an accumulator, which starts at
Step 2: Return and Display the Reduced Value
- The reduced value (sum or concatenated string) is returned by the function and printed using
console.log().
Custom Reductions
You can customize the reduction logic. For example, to find the product of all numbers in an array:
function productArray(arr) {
return arr.reduce((accumulator, currentValue) => accumulator * currentValue, 1);
}
To find the maximum number in an array:
function maxArray(arr) {
return arr.reduce((max, currentValue) => (currentValue > max ? currentValue : max), arr[0]);
}
Conclusion
This JavaScript program demonstrates how to reduce an array to a single value using the reduce() method. The reduce() method is highly versatile and can handle tasks such as summing, multiplying, concatenating, or finding the maximum value in an array. It is a powerful tool for aggregating data and performing operations across arrays.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment