angelina524
    • 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
# JS30 Day4 ## Array Cardio Day ###### tags: `JS 30` by Angelina --- ### Array * filter() [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) * map() [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) * sort() [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) * reduce() [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) --- ### Data ```htmlembedded= const inventors = [ { first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 }, { first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 }, { first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 }, { first: 'Marie', last: 'Curie', year: 1867, passed: 1934 }, { first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 }, { first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 }, { first: 'Max', last: 'Planck', year: 1858, passed: 1947 }, { first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 }, { first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 }, { first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 }, { first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 }, { first: 'Hanna', last: 'Hammarström', year: 1829, passed: 1909 } ]; const people = ['Beck, Glenn', 'Becker, Carl', 'Beckett, Samuel', 'Beddoes, Mick', 'Beecher, Henry', 'Beethoven, Ludwig', 'Begin, Menachem', 'Belloc, Hilaire', 'Bellow, Saul', 'Benchley, Robert', 'Benenson, Peter', 'Ben-Gurion, David', 'Benjamin, Walter', 'Benn, Tony', 'Bennington, Chester', 'Benson, Leana', 'Bent, Silas', 'Bentsen, Lloyd', 'Berger, Ric', 'Bergman, Ingmar', 'Berio, Luciano', 'Berle, Milton', 'Berlin, Irving', 'Berne, Eric', 'Bernhard, Sandra', 'Berra, Yogi', 'Berry, Halle', 'Berry, Wendell', 'Bethea, Erin', 'Bevan, Aneurin', 'Bevel, Ken', 'Biden, Joseph', 'Bierce, Ambrose', 'Biko, Steve', 'Billings, Josh', 'Biondo, Frank', 'Birrell, Augustine', 'Black Elk', 'Blair, Robert', 'Blair, Tony', 'Blake, William']; ``` --- * 有一個 invertors array,每個 invertor 都是一個物件 * 有一個 people array,裡面都是字串,每個字串都包含:姓氏 逗點 空白 名字 --- ### 題目 1. Filter the list of inventors for those who were born in the 1500's 2. Give us an array of the inventor first and last names 3. Sort the inventors by birthdate, oldest to youngest 4. How many years did all the inventors live? --- 5. Sort the inventors by years lived 6. create a list of Boulevards in Paris that contain 'de' anywhere in the name 7. sort Exercise:Sort the people alphabetically by last name 8. Reduce Exercise:Sum up the instances of each of these --- ### 第一題 #### Filter the list of inventors for those who were born in the 1500's * 找出於 1500~1599 年出生的 inventor * filter():用來過濾條件中的選項,並收集回傳是 true 的陣列 * `var newArray = arr.filter(callback)` --- ```javascript= const fifteen = inventors.filter(function(inventor) { if(inventor.year >= 1500 && inventor.year <= 1599) { return true } }) console.log(fifteen) console.table(fifteen) ``` ![](https://i.imgur.com/63YGFCJ.png) ![](https://i.imgur.com/SsDA0lN.png) --- * 利用 arrow function 箭頭函式簡化 ```javascript= const fifteen = inventors.filter(inventor => inventor.year >= 1500 && inventor.year <= 1599) ``` --- * const 宣告新的陣列 fifteen,這個陣列是從 inventors 的陣列過濾出來的,裡面包 callback function,會把 array 內符合條件是 1500~1599年出生的 inventor 都保留 (留下 true),形成一個新的 array * 可以用 arrow function 箭頭函式 --- ### 第二題 #### Give us an array of the inventor first and last names * 包含姓、名的陣列 * map():依條件組合物件中的內容,並回傳陣列 * `let new_array = arr.map(callback)` --- ```javascript= const fullNames = inventors.map(inventor => inventor.first+ '' + inventor.last) ``` * template strings 樣板字串 ```javascript= const fullNames = inventors.map(inventor => `${inventor.first} ${inventor.last}`); console.log(fullNames); ``` ![](https://i.imgur.com/SPfkOQE.png) --- * Map takes in an array, it does something with that array and then returns a new array but of the same length. * map 從一個陣列裡面拿東西,回傳一個陣列長度相同的新陣列 * filter 則會過濾,不符合條件的都踢掉,新陣列長度可能不會一樣喔 --- ### 第三題 #### Sort the inventors by birthdate, oldest to youngest * 排列最老到最年輕的 * sort():排序 * `arr.sort([compareFunction])` * 傳入兩個值 => return 正數、負數、0 * 正數換位置,負數不換位置,0 也是不換位置 --- ```javascript= const ordered = inventors.sort(function(a, b) { if(a.year > b.year) { return 1; } else { return -1; } }); ``` * 利用 Ternary Operator 三元運算子簡化 ```javascript= const ordered = inventors.sort((a, b) => a.year > b.year ? 1 : -1); console.table(ordered); ``` --- ![](https://i.imgur.com/b8zlR6W.png) --- * a 為第一個人,b 為第二個人,year 的數字越小,年齡越大 * return 1 會換位置,-1 不會換位置,0 相等不換位置 * 當 a.year 的數字 比 b.year 的數字大的時候,表示 a 比 b 小,回傳 1 就要換位置了 --- ### 第四題 #### How many years did all the inventors live? * 加總 inventors 的壽命 * 迴圈解法: ```javascript= let totalYears = 0 for(let i = 0; i < inventors.length; i++) { totalYears += (inventors[i].passed - inventors[i].year) } console.log(totalYear) ``` --- * reduce():累加數值 * `arr.reduce(callback, initialValue)` --- * reduce() 解法: ```javascript= const totalYears = inventors.reduce((total, inventor) => { return total + (inventor.passed - inventor.year); }, 0); console.log(totalYears); ``` ![](https://i.imgur.com/n3290pS.png) --- * 以前都會用迴圈,宣告變數,從 inventor 第一個跑到最後一個加總,最後輸出 * reduce(callback, 初始值),與 sort 一樣,裡面放一個 callback function,第一個存數值,第二放上 item,回傳則為壽命的計算式,最後則為數值計算的初始值 --- ### 睡著了嗎? --- ### 你敢睡??? --- ### 牛刀小試 #### 下列何者是用於排序? ( A ) filter ( B ) sort --- ### 牛刀小試 #### 下列何者是用於累計? ( A ) reduce ( B ) map --- ### 牛刀小試 #### 下列何者不用 callback? ( A ) reduce ( B ) map ( C ) filter ( D ) sort ( E ) 以上皆非 ( F ) 以上皆是 --- ### 第五題 #### Sort the inventors by years lived * 排列壽命的長短,由最長到最短 * sort() --- (未處理相等情況) ```javascript= const oldest = inventors.sort((a, b) => { const lastGuy = a.passed - a.year; const nextGuy = b.passed - b.year; return lastGuy > nextGuy ? -1 : 1 ; }) console.table(oldest) ``` ![](https://i.imgur.com/wFulqX6.png) --- * sort + 三元運算子 * 每個傳入的人,計算壽命後,進行排列,a 的壽命比 b 長,則回傳 -1,表示不換位置,回傳 1 要換位置,由最長的排列至最短的壽命 --- ### 第六題 #### create a list of Boulevards in Paris that contain 'de' anywhere in the name https://en.wikipedia.org/wiki/Category:Boulevards_in_Paris * 包含 de 的名字 * 開啟 dev tool,從網頁中用 querySelector 的方式抓 DOM 元素 --- * 找到要抓的內容 ![](https://i.imgur.com/eQd6Wj3.jpg) --- ```javascript= const category = document.querySelector('.mw-category'); ``` ![](https://i.imgur.com/haMk3fl.png) --- ```javascript= const category = document.querySelector('.mw-category'); const links = category.querySelectorAll('a'); ``` ![](https://i.imgur.com/GFJO1ho.png) --- * 從每個 link 裡面拿到 name ```javascript= const category = document.querySelector('.mw-category'); const links = category.querySelectorAll('a'); const de = links.map(link => link.textContent); ``` ![](https://i.imgur.com/iAesspn.png) * querySelectorAll 方法回傳一個類似陣列的物件稱為 Node List。這些資料結構簡稱為「類陣列」,因為他們和陣列很相似,但是不能使用陣列的方法像是 map 和 forEach --- ```javascript= const category = document.querySelector('.mw-category'); const links = Array.from(category.querySelectorAll('a')); //const links = [...category.querySelectorAll('a')] const de = links.map(link => link.textContent) ``` * 重整後再丟一次程式碼 ![](https://i.imgur.com/5BwlMmd.png) --- ### 牛刀小試 #### 下列何者是用於過濾? ( A ) file ( B ) filled ( C ) filter ( D ) full --- * filter() 將包含 de 的過濾出來 * 選取網頁中含有de的的街道,使用.includes('de') ```javascript= const category = document.querySelector('.mw-category'); const links = Array.from(category.querySelectorAll('a')); const de = links .map(link => link.textContent) .filter(streetName => streetName.includes('de')); ``` ![](https://i.imgur.com/jLQZIqL.png) --- #### 有時間再看: * [HTMLCollection與NodeList](https://codertw.com/%E5%89%8D%E7%AB%AF%E9%96%8B%E7%99%BC/28406/) * [將 Node List 轉換成陣列](https://www.jstips.co/zh_tw/javascript/converting-a-node-list-to-an-array/) --- ### 第七題 #### sort Exercise:Sort the people alphabetically by last name * 對 people 陣列的姓,進行排序 * split() 方法是依據給的內容拆分 string 成 array --- * sort() 排序 ```javascript= const alpha = people.sort((lastOne, nextOne) => { console.log(lastOne, nextOne) }); ``` ![](https://i.imgur.com/j9nG88a.png) --- * split() 內容拆分 string 成 array ```javascript= const alpha = people.sort((lastOne, nextOne) => { const parts = lastOne.split(', ') console.log(parts) }); ``` ![](https://i.imgur.com/c2OKUip.png) --- * Destructuring assignment 解構賦值語法,可以把陣列或物件中的資料解開擷取成為獨立變數 ```javascript= const alpha = people.sort((lastOne, nextOne) => { const [last, first] = lastOne.split(', '); console.log(last, first) }); ``` ![](https://i.imgur.com/cBxaGUX.png) --- * a, b 比較,依照 lastname 的字母順序排列 ```javascript= const alpha = people.sort((lastOne, nextOne) => { const [aLast, aFirst] = lastOne.split(', '); const [bLast, bFirst] = nextOne.split(', '); return aLast > bLast ? 1 : -1; }); console.log(alpha); ``` ![](https://i.imgur.com/Qm3dz3R.png) --- ### 第八題 #### Reduce Exercise:Sum up the instances of each of these * 計算陣列內重複的個數 ```javascript= const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck', 'pogostick']; ``` --- * 初始值位置放上空物件{},代表回傳的是一個物件 ```javascript= const transportation = data.reduce((obj, item) => { if (!obj[item]) { obj[item] = 0; } obj[item]++; return obj; }, {}); console.log(transportation) ``` ![](https://i.imgur.com/GmDcKj8.png) --- ### 參考資料 / 資源 * [javascript30](https://javascript30.com/) * [start / finished file](https://github.com/wesbos/JavaScript30/tree/master/04%20-%20Array%20Cardio%20Day%201) * [Javascript30-dustin](https://dustinhsiao21.github.io/Javascript30-dustin/) --- ### 感謝收聽,下回再見

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