{"id":21964687,"url":"https://github.com/mosnad-web01/abdulaziz-phase-1-using-array-reduce","last_synced_at":"2026-05-05T03:34:50.513Z","repository":{"id":262851713,"uuid":"844983331","full_name":"Mosnad-Web01/abdulaziz-phase-1-using-array-reduce","owner":"Mosnad-Web01","description":null,"archived":false,"fork":false,"pushed_at":"2024-08-20T10:59:42.000Z","size":35,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-01-28T01:17:11.255Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Mosnad-Web01.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-08-20T10:58:37.000Z","updated_at":"2024-08-20T10:59:46.000Z","dependencies_parsed_at":"2024-11-15T00:46:17.675Z","dependency_job_id":"43cee44a-1a24-479c-8750-2159c91cdcf0","html_url":"https://github.com/Mosnad-Web01/abdulaziz-phase-1-using-array-reduce","commit_stats":null,"previous_names":["mosnad-web01/abdulaziz-phase-1-using-array-reduce"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Mosnad-Web01%2Fabdulaziz-phase-1-using-array-reduce","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Mosnad-Web01%2Fabdulaziz-phase-1-using-array-reduce/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Mosnad-Web01%2Fabdulaziz-phase-1-using-array-reduce/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Mosnad-Web01%2Fabdulaziz-phase-1-using-array-reduce/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Mosnad-Web01","download_url":"https://codeload.github.com/Mosnad-Web01/abdulaziz-phase-1-using-array-reduce/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245021743,"owners_count":20548396,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-29T12:26:52.748Z","updated_at":"2026-05-05T03:34:50.480Z","avatar_url":"https://github.com/Mosnad-Web01.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Using the Array Reduce Method\n\n## Learning Goals\n\n- Learn how the `reduce()` method works\n- Demonstrate using `reduce()` with a primitive return value\n- Demonstrate using `reduce()` with an object as the return value\n\n## Introduction\n\nIn the world of programming, we often work with lists. Sometimes we want to find\nor transform elements in a list, but other times we might want to create a\nsingle summary value. In this lesson, we'll learn how to use the `reduce()`\niterator method to **aggregate** a result, i.e., to _reduce_ a list to a single\nvalue. That value can be a string, a number, a boolean, etc.\n\nTo better understand how `reduce()` works, we'll start by building our own\nversion.\n\n## Learn How the `reduce()` Method Works\n\nLet's say we have a bunch of grocery items in our basket and we want to\ncalculate the total price. Our basket data might look like this:\n\n```js\nconst products = [\n  { name: \"Shampoo\", price: 4.99 },\n  { name: \"Donuts\", price: 7.99 },\n  { name: \"Cookies\", price: 6.49 },\n  { name: \"Bath Gel\", price: 13.99 },\n];\n```\n\nWe're going to _reduce_ the array of products to a _single value_: the total\nprice. To do this, we'll create a `getTotalAmountForProducts()` function:\n\n```js\nfunction getTotalAmountForProducts(products) {\n  let totalPrice = 0;\n\n  for (const product of products) {\n    totalPrice += product.price;\n  }\n\n  return totalPrice;\n}\n\nconsole.log(getTotalAmountForProducts(products)); // LOG: 33.46\n```\n\nWe first declare a `totalPrice` variable and set its initial value to 0. We then\niterate through the products in the basket and add the price of each to the\ntotal. When the loop has finished, we return the `totalPrice`.\n\nThis is a very basic way to manually add together the prices of the products we\nwant to buy, but it only works for this very specific situation. We could make\nour solution more abstract by writing a generalized function that accepts two\nadditional arguments: an initial value and a callback function that implements\nthe reduce functionality we want.\n\nTo see what this might look like, let's count the number of coupons we have\nlying around the house:\n\n```js\nconst couponLocations = [\n  { room: \"Living room\", amount: 5 },\n  { room: \"Kitchen\", amount: 2 },\n  { room: \"Bathroom\", amount: 1 },\n  { room: \"Master bedroom\", amount: 7 },\n];\n\nfunction ourReduce(arr, reducer, init) {\n  let accum = init;\n  for (const element of arr) {\n    accum = reducer(accum, element);\n  }\n  return accum;\n}\n\nfunction couponCounter(totalAmount, location) {\n  return totalAmount + location.amount;\n}\n\nconsole.log(ourReduce(couponLocations, couponCounter, 0)); // LOG: 15\n```\n\n`ourReduce()` accepts three arguments: the array we want to reduce, the callback\nfunction or _reducer_, and the initial value for our _accumulator_ variable.\nIt then iterates over the array, calling the reducer function each time, which\nreturns the updated value of the accumulator. The final value of the accumulator\nis returned at the end.\n\nNote that `ourReduce()` is generalized: the specifics (the callback function and\ninitial value) have been abstracted out, making our code more flexible. If, for\nexample, we already have three coupons in our hand, we can easily account for\nthat without having to change any code by adjusting the initial value when we\ncall `ourReduce()`:\n\n```js\nconsole.log(ourReduce(couponLocations, couponCounter, 3)); // LOG: 18\n```\n\n## Demonstrate using `reduce()` with a Primitive Return Value\n\nWith JavaScript’s native `reduce()` method, we don't need to write our own\nversion. Just like `ourReduce`, the `reduce()` method is used when we want to\nget some information from each element in the collection and gather that\ninformation into a final summary value. Let's take the native implementation for\na spin with our previous example:\n\n```js\nconsole.log(couponLocations.reduce(couponCounter, 0)); // also logs 15!\n```\n\nAnother simple numerical example:\n\n```js\nconst doubledAndSummed = [1, 2, 3].reduce(function (accumulator, element) {\n  return element * 2 + accumulator;\n}, 0);\n// =\u003e 12\n```\n\nHere, as in the previous example, we are calling `.reduce()` on our input array\nand passing it two arguments: the callback function, and an optional start value\nfor the accumulator (0 in this example). `.reduce()` executes the callback for\neach element in turn, passing in the current value of the accumulator and the\ncurrent element each time. The callback updates the value of the accumulator in\neach iteration, and that updated value is then passed as the first argument to\nthe callback in the next iteration. When there's nothing left to iterate, the\nfinal value of the accumulator (the total) is returned.\n\nThe initialization value is optional, but leaving it out might lead to a real\nsurprise. If no initial value is supplied, the _first element in the array_ is\nused as the starting value. `reduce()` then executes the callback function,\npassing this starting value and the _second_ element of the array as the two\narguments. In other words, the code inside the callback **is never executed**\nfor the first element in the array. This can lead to unexpected results:\n\n```js\nconst doubledAndSummed = [1, 2, 3].reduce(function (accumulator, element) {\n  return element * 2 + accumulator;\n});\n// =\u003e 11\n```\n\nIn some cases, it won't matter (e.g., if our reducer is simply summing the\nelements of the input array). However, to be safe, it is best to always pass a\nstart value when calling `reduce()`. Of course, that initial value can be\nanything we like:\n\n```js\nconst doubledAndSummedFromTen = [1, 2, 3].reduce(function (\n  accumulator,\n  element\n) {\n  return element * 2 + accumulator;\n},\n10);\n// =\u003e 22\n```\n\n## Demonstrate using `reduce()` with an Object as the Return Value\n\nThe output of the `reduce()` method does not need to be a primitive value like a\n`Number` or `String`. Let's consider a couple of examples that accumulates array\nvalues into an `Object`.\n\nFirst, let's look at an example where we take an array of letters and return\nan object with letters as keys and their count in the array as values.\n\n```js\nconst letters = [\"a\", \"b\", \"c\", \"b\", \"a\", \"a\"];\n\nconst lettersCount = letters.reduce(function (countObj, currentLetter) {\n  if (currentLetter in countObj) {\n    countObj[currentLetter]++;\n  } else {\n    countObj[currentLetter] = 1;\n  }\n  return countObj;\n}, {});\n\nconsole.log(lettersCount); // { a: 3, b: 2, c: 1 }\n```\n\nWe initialize the `countObj` as an empty object by passing `{}` as the second\nargument to the `reduce` method. The callback method increments the current\nletter's count in the `countObj` if it already exists otherwise, initializes it to\n`1`.\n\nLet's look at a more complex example now. Say we want to create a roster of\nstudent artists based on their discipline of art for their final showcase.\nOur start value might look like this:\n\n```js\nconst artsShowcases = {\n  Dance: [],\n  Visual: [],\n  Music: [],\n  Theater: [],\n  Writing: [],\n};\n```\n\nImagine we also have a `studentSorter` object that includes a `showcaseAssign()`\nmethod. That method takes the name of a student as its argument and returns the\nname of the showcase the student should be assigned to. Note that we have not\ncoded out the `showcaseAssign()` method — the details of how it would work are\nnot important for our purposes. What's important to remember is that the method\ntakes the name of a student as an argument and returns one of the five showcases:\n\"Dance\", \"Visual\", \"Music\", \"Theater\" or \"Writing\". We want to call the method\nfor each element in our input array (each student's name), get the value of the\nshowcase that's returned, and add the student's name to the array for that\nshowcase in the `artsShowcases` object.\n\nTo do that, we will call reduce on our input array, `incomingStudents`, which\ncontains the names of all incoming students, passing a callback function and the\nstart value of `artsShowcases` as the arguments. The callback is where we'll\npush each student name into the appropriate showcase:\n\n```js\nincomingStudents.reduce(function (showcases, student) {\n  showcases[studentSorter.showcaseAssign(student)].push(student);\n}, artsShowcases);\n```\n\nLet's break this down: `.reduce()` executes the callback for each student name\nin turn. Inside the callback, the `studentSorter.showcaseAssign()` method is\ncalled with the current student name as its argument. `showcaseAssign()` returns\nthe name of an Arts Showcase, which is then used as the key to access the\ncorrect array in the `artsShowcases` object and push the student's name into it.\nThe iteration then continues to the next element in the array, passing the next\nstudent name and the updated value of `artsShowcases` as the arguments. Once\n`reduce()` has iterated through all the students in `incomingStudents`, it\nreturns the final value of `artsShowcases`.\n\nWe can then access the list of students in any Arts Showcase:\n\n```js\nartsShowcases[\"Visual\"]; //=\u003e [yishayGarbasz, wuTsang, mickaleneThomas]\n```\n\n## Lab: Use `reduce()` to Create a Single Aggregate of All Items in a List\n\nLet's say we are hard at work in the battery factory. We've assembled several\nbatches of batteries today. Let's count how many assembled batteries we ended\nup with.\n\n- Create a new variable called `totalBatteries`, which holds the sum of all of\n  the battery amounts in the `batteryBatches` array. (Note that the\n  `batteryBatches` variable has been provided for you in `index.js`.) Naturally,\n  you should use `reduce()` for this!\n\nRemember the workflow:\n\n1. Install the dependencies using `npm install`.\n2. Run the tests using `npm test`.\n3. Read the errors; vocalize what they're asking you to do.\n4. Write code; repeat steps 2 and 3 often until a test passes.\n5. Repeat as needed for the remaining tests.\n\nAfter you have all the tests passing, remember to commit and push your changes\nup to GitHub, then submit your work to Canvas using CodeGrade.\n\n## Conclusion\n\nWith `reduce()`, we are able to quickly get a single summary value from the\nelements in an array. `reduce()` — like the other iterator methods we've learned\nabout in this section — can greatly cut down the amount of time spent recreating\ncommon functionality. It can also make our code more efficient and expressive.\n\n## Resources\n\n- [MDN: Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmosnad-web01%2Fabdulaziz-phase-1-using-array-reduce","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmosnad-web01%2Fabdulaziz-phase-1-using-array-reduce","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmosnad-web01%2Fabdulaziz-phase-1-using-array-reduce/lists"}