Skip to content

Instantly share code, notes, and snippets.

@ptomato
Created February 11, 2021 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ptomato/fe650f79f94dbe2591cb3d6f5b0882fb to your computer and use it in GitHub Desktop.
Save ptomato/fe650f79f94dbe2591cb3d6f5b0882fb to your computer and use it in GitHub Desktop.
reduce() examples
// reduce()
// ========
// The way everyone starts out learning reduce() is by calculating
// the sum of an array of numbers:
const a = [1, 5, 16, 2, 7, 5, 16, 5];
// If we were going to calculate the sum of an empty array, then
// we'd want the answer to be 0. So that's what we use for the
// initial value:
// a.reduce(..., 0);
// Illustrate intermediate values by placing a log statement in
// the callback:
let sum = a.reduce((intermediate, element) => {
console.log(`callback called on (${intermediate}, ${element})`);
return intermediate + element;
}, 0);
console.log(sum)
// callback called on (0, 1)
// callback called on (1, 5)
// callback called on (6, 16)
// callback called on (22, 2)
// callback called on (24, 7)
// callback called on (31, 5)
// callback called on (36, 16)
// callback called on (52, 5)
// 57
// Without the log statement, the short way of writing it is:
a.reduce((intermediate, element) => intermediate + element, 0);
// Here's an example for returning an array with duplicates
// removed. For each element, the intermediate result is all
// of the unique elements from earlier in the array, with the
// element maybe pushed in if it doesn't already exist in
// there:
a.reduce((intermediate, element) => {
if (!intermediate.includes(element))
intermediate.push(element);
return intermediate;
}, []);
// [ 1, 5, 16, 2, 7 ]
// The simpler way to deduplicate array elements is to create
// a Set from the array and then spread it into an array
// again:
[...new Set(a)]
// [ 1, 5, 16, 2, 7 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment