I am sharing an example in this article, showing how to use both .reduce() and map() together in JavaScript to produce a result, without using nested loops.
Example:
Let us assume, I have a JSON array. The array has two different types of values: subject and marks.
I’ll filter the marks first, using JavaScript array.map() method and then calculate the total marks.
<script> let cal_total_marks = () => { const arr = [ {"Subject": "Math", "Marks": 87 }, {"Subject": "Science", "Marks": 91 }, {"Subject": "Sanskrit", "Marks": 83 } ]; const arrMarks = arr.map(students => students.Marks); const result = arrMarks.reduce(sum, 0); document.write (result); // Output: 261 } let sum = (prev, cur) => { return prev + cur; } cal_total_marks(); </script>
Why use both reduce() and map() together?
To improve efficiency. Although, both map() and reduce() have different usages, using together improves the efficiency of data manipulation.
The map() method tranforms array elements.
The reduce() method is used to accumulate values.
So, in the above example, the "map()" first transforms the data (tranforms each array element) and "reduce()" method calculates (or accumulates or aggregates) the tranformed data. In this way, you are separating the two logics. In some cases it improves the performance of the code.
Remember: The array.reduce() method does not alter the original array.