Skip to content

Instantly share code, notes, and snippets.

@baker-ling
Created July 12, 2022 04:46
Show Gist options
  • Save baker-ling/e5c3db68f606d67fefa228c361b6ec7b to your computer and use it in GitHub Desktop.
Save baker-ling/e5c3db68f606d67fefa228c361b6ec7b to your computer and use it in GitHub Desktop.
JavaScript Array method cheatsheet

JavaScript Array Method CheatSheet

  1. .forEach()
  2. .map()
  3. .filter()
  4. .reduce()

.forEach()

  • Purpose: basic alternative to the for loop that bypasses use of array indexes
  • Use when: you need to do an operation with side-effects (like writing to a file, outputting something on screen, adding content directly to the DOM)
  • Returns: undefined
  • Syntax:
myArray.forEach((element, index, array) => {
  // code with effects goes here
  // Note: index and array parameters are optional
});
  • Example:
const fs = require('fs')
const filenames = ['temp1.txt', 'temp2.txt', 'temp3.txt']
// delete files in the array
filenames.forEach(filename => {
  fs.rm(filename,
        err => console.log(err ? `Failed to delete ${filename}` : `Successfully deleted ${filename}`)
       ); 
})

.map()

  • Purpose: to transform an array of values into a new array of values
  • Use when: you have a list of things that you need to transform item by item into another list
  • Returns: a new array of values output by the callback function
  • Syntax:
myArray.map((element, index, array) => {
  // code that returns a value goes here
  // Note: index and array parameters are optional
});
  • Example:
const cart = [
  {description: 'Apples', qty: 3, unitPrice: 1.09, taxCategory: 'food'},
  {description: 'Bread', qty: 1, unitPrice: 2.99, taxCategory: 'food'},
  {description: 'Beer, 6 pack', qty: 1, unitPrice: 9.99, taxCategory: 'alcohol'},
  {description: 'Scissors', qty: 1, unitPrice: 5.99, taxCategory: 'general'}
];
const taxRates = {
  'general': 0.10,
  'alcohol': 0.15,
  'food': 0.02
}
// Compute total cost per line item
const lineItemTotals = cart.map(item => {
  const {qty, unitPrice, taxCategory} = item;
  const taxCoefficient = 1 + taxRates[taxCategory];
  return qty * unitPrice * taxCoefficient;
});
// lineItemTotals: [ 3.3354000000000004, 3.0498000000000003, 11.4885, 6.589 ]

.filter()

  • Purpose: to filter values in an array based on some criteria
  • Use when: you have some criteria for filtering or continuing processing that you want to apply
  • Returns: a new array of values from the original array where the callback returned a truthy value
  • Syntax:
myArray.filter((element, index, array) => {
  // code that returns true or false (actually truthy or falsy) goes here
  // Note: index and array parameters are optional
});
  • Example:
const studentAbscences = [
  {name: 'John Doe', absences: 0},
  {name: 'Jack Black', absences: 4},
  {name: 'Roger Dodger', absences: 8},
  {name: 'Ray Ghost', absences: 60}
];
const MAX_ABSENCES = 8;
const eligibleStudents = studentTimesInClass.filter(studentData => {
  const {absences} = studentData;
  return absences <= MAX_ABSENCES;
});
// eligibleStudents: [
//  {name: 'John Doe', absences: 0},
//  {name: 'Jack Black', absences: 4},
//  {name: 'Roger Dodger', absences: 8}
// ]

.reduce()

  • Purpose: to convert an array of values to a single value (even an object)
  • Use when: you want to convert an array to a single value or object
  • Returns: a single value
  • Syntax:
myArray.reduce(
  (previousAccumulatedValue, currentValue, currentIndex, array) => { /* code that returns new accumulated value */ },
  initialValue
  // Note: currentIndex and array parameters are optional
});
  • Example:
const votes = [
  'John Doe',
  'Jack Black',
  'Roger Dodger',
  'Ray Ghost',
  'John Doe',
  'Jack Black',
  'Roger Dodger',
  'John Doe',
  'John Doe',
  'John Doe',
  'Jack Black',
  'Roger Dodger',
];
const initialTally = {};
const finalTally = votes.reduce(
  (runningTally, vote) => {
    if (!(vote in runningTally)) runningTally[vote] = 0;
    runningTally[vote] += 1;
    return runningTally; // don't forget to return the new accumulated value!
  },
  initialTally
)
// finalTally: {
//   'John Doe': 5,
//   'Jack Black': 3,
//   'Roger Dodger': 3,
//   'Ray Ghost': 1
// }
@tajajones2
Copy link

this is a BIG help! thank you Brian :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment