Skip to content

Instantly share code, notes, and snippets.

@ashx3s
Last active March 6, 2024 16:45
Javascript Reduce method

Reduce Method

  • reduce() takes a 'reducer' callback that you create and applies it to each element in an array

    • it passes the return value of each iteration forward
    • The end result is that all the elements will be reduced down into 1 value
  • Documentation

Uses of reduce()

  • add up all values in an array
  • add values from objects in an array of objects
  • flatten an array
  • group objects by property
  • It can replace chanining filter and map

Sum all numbers in an array

  • it tracks the previous value and adds the current value to it
const arr = [1, 2, 3, 4, 5]

arr.reduce((prev, curr) => prev + curr,0)

Sum numbers from array of objects

  • This follows the same principle, but you access the specific key value pairs with dot notation
const arr = [{x:2}, {x:1}]
arr.reduce((prev, curr) => prev.x + curr.x, 0 )
  • But for more complex arrays, it will look more like

Flatten an array of arrays (less common)

  • You might need to do this to simplify more complex data sets
  • Use .concat() between the previous and current values to turn a group of arrays into a single array
const arr = [[1,2][3,5][9,4]]
arr.reduce((prev, curr) => prev.concat(curr))

Group objects by a property (advanced)

  • See more about this in the mdn docs linked at the top of this gist. The following function is used in the mdn example
const groceries = [
  {
    product: 'Cabbage',
    cost: 4.32,
    type: 'vegetable'
  },
  {
    product: 'Chicken',
    cost: 8.50,
    type: 'meat'
  },
  {
    product: 'Spinach',
    cost: 6.22,
    type: 'vegetable'
  }
]

// create a function to group by a specific property

function groupProducts(arr, prop) {
  return arr.reduce((acc, curr) => {
    let key = curr[prop];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(curr)
    return acc
  }, {})
}

Reduce Activities

Mild

  1. Create an array of numbers
  2. use .reduce() to add them all together

Medium

  1. Use the grocery array from yesterday
  2. Sum up all the values before tax with an anonymous function
  3. Creat a sum function and then use it in the .reduce() method on your grocery list
  4. Use reduce on the values that have tax added to them as well

Spicy

  1. Review the cody to group items in an array by a property
  2. Add a property to each object in your array to group items
  3. Try to group your grocery items by the category
  4. Try creating another parameter to group them (like all products under 5.00)
// reduce can be used to add up all the items in an array
const arr = [1, 2, 3];
// sum function
function sum(accumulator, current) {
return accumulator + current;
}
// reduce to return the sum
const total = arr.reduce(sum, 0);
const groceries = [
{
product: "Cabbage",
cost: 4.32,
type: "vegetable",
},
{
product: "Chicken",
cost: 8.5,
type: "meat",
},
{
product: "Spinach",
cost: 6.22,
type: "vegetable",
},
];
groceries.reduce((accumulator, current) => accumulator + current.cost, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment