How to use Array reduce() Method In JavaScript
The Javascript Array reduce() method is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator.
Syntax:
arrayName.reduce(()=>{});
Example: The below code uses a JavaScript function with the Array reduce() method to iterate through numbers and return a string message if the sum is negative.
Javascript
function sumChecker(numbers) { const sum = numbers.reduce((acc, num) => acc + num, 0); if (sum < 0) { return `The sum of the numbers is ${sum}, and is negative.`; } else { return `The sum of the numbers is ${sum}, and is positive.`; } } console.log(sumChecker([1, -2, 3, -4, -5])); console.log(sumChecker([1, 4, 5, -3, 2])); |
The sum of the numbers is -7, and is negative. The sum of the numbers is 9, and is positive.
How to Iterate Through Numbers and Return a String Message if the Sum is Negative?
In JavaScript, iterating through numbers or any kind of iterable data structures is a common programming task. The ability to repeat a certain block of code multiple times allows you to perform operations on a set of data. We can iterate through an array of numbers and return a string message if the sum of the numbers is negative.
Table of Content
- Using JavaScript For Loop
- Using JavaScript For Of Loop
- Using JavaScript While Loop
- Using JavaScript Array forEach() Method
- Using JavaScript Array reduce() Method