Joe Stephens
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
# Array Iterators These are the most commonly used array iterators. We've also provided examples of how and where you might use them. You may want to read the byte on [callback functions](callback-functions.md) first. * [forEach](#forEach) * [map](#map) * [filter](#filter) * [find](#find) * [indexOf](#indexOf) * [reduce](#reduce) * [sort](#sort) # forEach The `.forEach` method iterates over every element in an array and every time it lands on an element it will call the callback function you provide, passing 3 arguments to your callback function's parameters (in order): * `currentValue` - the value of the current element * `index` - the index of the current element in the given array * `array` - the array being iterated over (if you've assigned your array to a variable then you usually won't need this parameter) ## When to use `forEach` `forEach` is great for when you want to iterate over an array and access one element at a time without modifying it's value. ## Example Scenario Imagine a website such as _MailChimp_, where a business can create a mailing list that customers can sign up to. That business might create a new newsletter, which they want to send out to all of their customers. A `forEach` in this scenario might be used to iterate over the mailing list and to call a `sendEmail` function for each email. ### Code ```js const sendEmail = (emailAddress) => { // you don't need to worry about what sendEmail might look like } const emails = [ 'mthurn@live.com', 'rgarcia@optonline.net', 'webdragon@comcast.net', 'crandall@sbcglobal.net', 'fangorn@hotmail.com' ] emails.forEach((email, index) => { console.log('Sending newsletter to ' + email + ' - index ' + index + ' in the list of emails') sendEmail(email) }) ``` ## [forEach on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) # map The `.map` method iterates over each element in an array, calling a callback function you provide. The return value of this function gets appended to a new array (`map` doesn't mutate the original array). 3 arguments get passed to your callback function: * `currentValue` - the value of the current element * `index` - the index of the current element in the given array * `array` - the array being iterated over (if you've assigned your array to a variable then you usually won't need this parameter) ## When to use `map` `map` is great for when you want to create a new array of elements where each element has been calculated from (and corresponds to) an element in a different array. ## Example Scenario A teacher has reports for all of their students. Each report has their name, grade and attendance. Ofsted are inspecting the school and have asked for an anonymised list of grades. We could use a `map` in this scenario to iterate over every `report` in a `reports` array. The callback function we provide will be passed a `report`. We can return `report.grade` from that callback function to create a new array with just grades. ### Code ```js const reports = [{ name: 'Jimmy', grade: 'B', attendance: 96 }, { name: 'Thelma', grade: 'A', attendance: 100 }, { name: 'Aimee', grade: 'C', attendance: 85 }, { name: 'Lee', grade: 'D', attendance: 72 }] const grades = reports.map(report => report.grade) console.log(grades) // ['B', 'A', 'C', 'D'] ``` ## [map on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) # filter The `.filter` method iterates over each element in an array, calling a callback function you provide. If your callback function returns `true` then the current element being iterated over gets added to a new array (`filter` doesn't mutate the original array). 3 arguments get passed to your callback function: * `currentValue` - the value of the current element * `index` - the index of the current element in the given array * `array` - the array being iterated over (if you've assigned your array to a variable then you usually won't need this parameter) ## When to use `filter` `filter` is great for when you want to create a new array of elements (from another array) where all of the elements have met a condition you've set. ## Example Scenario You're shopping for a laptop on eBay, and you're only interested in laptops running Windows XP. You could use `filter`, and pass a callback function that returns `true` if the `currentValue` (current laptop being iterated over) has an `operatingSystem` property with a value of `Windows XP`. ### Code ```js const laptops = [{ model: 'Dell Inspiron', operatingSystem: 'Windows XP', price: 1250 }, { model: 'Microsoft Surface Pro', operatingSystem: 'Windows 10', price: 800 }, { model: 'Lenovo Thinkpad', operatingSystem: 'Ubuntu', price: 250 }, { model: 'Toshiba Satellite', operatingSystem: 'Windows XP', price: 400 }] const windowsXPLaptops = laptops.filter(laptop => { laptop.operatingSystem === 'Windows XP' }) console.log(laptops) // [ // { model: 'Dell Inspiron', operatingSystem: 'Windows XP', price: 1250 }, // { model: 'Toshiba Satellite', operatingSystem: 'Windows XP', price: 400 } // ] ``` ## [filter on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) # find The `.find` method iterates over each element in an array until the callback function you provide returns `true` indicating a record has met criteria you've specified. `find` passes 3 arguments to your callback function's parameters (in order): * `currentValue` - the value of the current element * `index` - the index of the current element in the given array * `array` - the array being iterated over (if you've assigned your array to a variable then you usually won't need this parameter) ## When to use `find` `find` is great when you have a scenario in which you need to retrieve an element from an array and you don't know it's index. ## Example Scenario A local library has books, each of which has an ISBN. Their online e-library system allows members to search for a book by its ISBN and if there is a book (or many books with the same ISBN) then a member can take one out. ### Code ```js const books = [ { name: 'The Wizard of Oz', isbn: '540290' }, { name: 'Pride and Prejudice', isbn: '094290' }, { name: 'Pride and Prejudice', isbn: '094290' }, { name: 'Harry Potter', isbn: '193375' } ] const findBookByIsbn = (isbn, books) => { return books.find(book => book.isbn === isbn) } findBookByIsbn('094290', books) // { name: 'Pride and Prejudice', isbn: '094290' } ``` (Note: there are two Pride and Prejudice books. The one returned will be the one at index 1 as its the first one found) ## [find on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) # indexOf `indexOf` iterates over an array until it finds the given element, at which point it returns the element's index, or `-1` if the element doesn't exist. Unlike other array iterator methods, it doesn't take a callback. It has the following parameters: * `searchElement` - the element you want to find the index for * `fromIndex`- the index to start searching from. Defaults to `0` if not specified. ## When to use `indexOf` Use `indexOf` if you need to find an element's index in order to use other array methods such as [splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) (a.k.a deleting an element from an array), or if you want to ensure you don't push a duplicate item into an array. ## Example Scenario Sandra collects coins, but her coin book only has a single slot for each coin. Therefore, if we imagine Sandra's coin book as an array, then we have to ensure Sandra can't _push_ the same coin twice. ### Code ```js const coins = [{ denomination: 50, year: 2012, name: 'Olympic 50p' }, { denomination: 200, year: 2005, name: 'Guy Fawkes £2' }, { denomination: 2, year: 1983, name: 'New Pence Two Pence' }] const addCoin = (coin, coinBook) => { const coinExists = coinBook.indexOf(coin) if (coinExists !== -1) { throw new Error('Coin already exists!') } coinBook.push(coin) } const sandrasCoinBook = [] addCoin(coins[0], sandrasCoinBook) addCoin(coins[0], sandrasCoinBook) // Error: Coin already exists! ``` [find](./find.md) could be used instead in the above scenario. ## Example Scenario Sandra's Mum has found a rare coin that Sandra has been searching for desperately, and rushes over to her house to surprise her. Sandra has already found this coin though. In order to avoid disappointing her Mum, she scrambles over to her coinbook and attempts to find the coin so she can hide it. Given the coin, we need to find it's index so we can _splice_ it from the coinbook. ### Code ```js const coins = [{ denomination: 50, year: 2012, name: 'Olympic 50p' }, { denomination: 200, year: 2005, name: 'Guy Fawkes £2' }, { denomination: 2, year: 1983, name: 'New Pence Two Pence' }] const removeCoin = (coin, coinBook) => { const coinToRemove = coinBook.find(existingCoin => existingCoin.name === coin.name) const existingCoinIndex = coinBook.indexOf(coinToRemove) return coinBook.splice(existingCoinIndex, 1) } const sandrasCoinBook = [{ denomination: 50, year: 2012, name: 'Olympic 50p' }] removeCoin({ denomination: 50, year: 2012, name: 'Olympic 50p' }, sandrasCoinBook) console.log(sandrasCoinBook) // [] ``` We use `find` above because objects are unique. Sandra's 50p and her Mum's 50p are both the same rare specification, but they are different coins. In JavaScript, the object we have as an element in `sandrasCoinBook` is different to the object we pass to `removeCoin`. It is recommended for this reason that if you are working with objects in arrays, that you always use `find` in combination with `indexOf`. ## [indexOf on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) # reduce `reduce` has an accumulator, which - every time an element is iterated over - is modified. When iteration of the array has finished, the `reduce` returns the final value of the accumulator. `reduce` passes 4 arguments to your callback function's parameters (in order): * `accumulator` - the accumulator to modify on each iteration * `currentValue` - the value of the current element * `index` - the index of the current element in the given array * `array` - the array being iterated over (if you've assigned your array to a variable then you usually won't need this parameter) In addition to the callback function, the `reduce` function has a second parameter of `initialValue`. The argument passed is the starting value of `accumulator` (it defaults to the first element in the array otherwise). ## When to use `reduce` The most common use case is when calculating totals, but there are many cool things you can do with `reduce`. Check out [How JavaScript’s Reduce method works, when to use it, and some of the cool things it can do](https://medium.freecodecamp.org/reduce-f47a7da511a9) on Free Code Camp. ## Example Scenario Chelsie has just started University, and needs to budget how much disposable income she'll have left from her maintenance loan a week after expenses. Chelsie's maintenance loan is £200 a week. Note that the example uses pence units, as to prevent any issues that might occur due to decimal precision - read [this article](http://adripofjavascript.com/blog/drips/avoiding-problems-with-decimal-math-in-javascript.html). ### Code ```js const expenses = [{ type: 'rent', amount: 15000 }, { type: 'food', amount: 3000 }, { type: 'books', amount: 1000 }, { type: 'laundry', amount: 500 }, { type: 'travel', amount: 1500 }] const amountRemaining = expenses.reduce((accum, expense) => accum - expense.amount, 20000) console.log(amountRemaining / 100) // -10 ``` ## [reduce on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) # sort `sort` will sort elements in an array. It has an optional parameter of `compareFunction`, which determines the sort order. If `compareFunction` isn't provided, then `sort` will convert all elements in the array to strings and compare them in Unicode point order (uppercase letters come before lowercase letters). The `compareFunction` callback has 2 parameters `a`, and `b`. `a` is the element currently being iterated over, and `b` is the next element in the array. If `compareFunction` returns `0` then their positions in the array will stay the same. If it returns less than `0` then `a` will come before `b`. If it returns greater than `0` then `b` will come before `a`. `sort` mutates the original array. ## When to use `sort` Any scenario in which you need to present data in a particular order, or run a process on data in a particular order. ## Example Scenario On Amazon, the default product sort order is by relevance to the search term. We can use `sort` on an array of products to sort products by lowest price first. ### Code ```js const headphones = [{ name: 'Apple Airpods', price: 15000 }, { name: 'Sony Headphones', price: 5000 }, { name: 'Marshall Headphones', price: 6000 }] headphones.sort((headphonesA, headphonesB) => headphonesA.price - headphonesB.price) console.log(headphones) // [ // { name: 'Sony Headphones', price: 5000 }, // { name: 'Marshall Headphones', price: 6000 } // { name: 'Apple Airpods', price: 15000 }, // ] ``` If `headphonesA` is the object for `Apple Airpods` and `headphonesB` is the object for `Sony Headphones` then the `compareFunction` formula will be `15000 - 5000` which equals `10000`. `10000` is greater than `0` so `headphonesB` gets moved in front of `headphonesA` in the array. ## [sort on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully