iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 4
0
自我挑戰組

新手村-30 Day JS Coding Challenge系列 第 4

新手村04 - Array Cardio Day 1

04 - Array Cardio Day 1

俗話說的好,一天一蘋果,醫生遠離我

一天一 JS,What the f*ck JavaScript?

small steps every day - 記錄著新手村日記

完成目標

Javascript基本的Array方法運用:

  • 運用高階函式的三大支柱:map、filter、reduce 處理 inventorspeople 陣列

  • 每一題會指定一個 Array Method,透過 console.log / console.table(不支援IE喔!)來解題

  • 小試身手一題

index_START.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Array Cardio ?</title>
</head>
<body>
  <p><em>Psst: have a look at the JavaScript Console</em> ?</p>

  <script>
    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'];

    // Array.prototype.filter()
    // 1. Filter the list of inventors for those who were born in the 1500's

    // Array.prototype.map()
    // 2. Give us an array of the inventors' first and last names

    // Array.prototype.sort()
    // 3. Sort the inventors by birthdate, oldest to youngest

    // Array.prototype.reduce()
    // 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
    // https://en.wikipedia.org/wiki/Category:Boulevards_in_Paris


    // 7. sort Exercise
    // Sort the people alphabetically by last name

    // 8. Reduce Exercise
    // Sum up the instances of each of these
    const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];

  </script>
</body>
</html>

JS

  • console.table(data [, columns])

    data:必須是 Array || Hash 、 columns:一個包含列的名稱和 Array

    試著在 console 中玩玩看這個範例:

    console.table(["apples", "oranges", "bananas"]);
    

    陣列裡面包含物件的範例:

    function Person(firstName, lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
    }
    
    var john = new Person("John", "Smith");
    var jane = new Person("Jane", "Doe");
    var emily = new Person("Emily", "Jones");
    
    console.table([john, jane, emily]);
    

JS - step by step

  1. 從 inventors 的變數中透過 filter 找出出生在15世紀的人:

    • filter:篩選抽出符合條件的保留下來,成為新的一個陣列,不會影響到原始資料(回傳是True或False)

      Array.prototype.filter():https://ubin.io/NV9EDk

    let fifteen = inventors.filter(function(inventor){
      return inventor.year >= 1500 && inventor.year < 1600
    })
    console.table(fifteen)
    
  2. 從 inventors 的變數中透過 map 合併 inventors' first and last names:

    • map:一樣產生一個新陣列,新陣列會紀錄回傳新的內容

      Array.prototype.map():https://ubin.io/cdqWhm

    let fullnames = inventors.map(function(inventor){
      return inventor.first + ' ' + inventor.last
    })
    console.table(fullnames)
    
  3. 從 inventors 的變數中透過 sort 排序 year 欄位由小至大:

    • sort:對一個陣列的所有元素進行排序,並回傳此陣列

      Array.prototype.sort():https://ubin.io/62RcBV

    let ordered = inventors.sort(function(a, b){
      return a.year > b.year ? 1 : -1
      // compareFunction(a, b) 的回傳值若小於 0,即 a 排在 b 前面,反之
    })
    console.table(ordered)
    
  4. 從 inventors 的變數中透過 reduce 算出每個人各活了多久:

    • reduce:累加器 total 及陣列中每項元素(由左至右)傳入回呼函式並將陣列化為單一值

      Array.prototype.reduce():https://ubin.io/Rgsbh1

    let totalYears = inventors.reduce(function(total,inventor){
      return total + (inventor.passed - inventor.year)
    }, 0) // 初始值
    console.log(totalYears)
    
  5. 從 inventors 的變數中透過 sort 排序活得長至短:

    • 結合上方的 sortreduce 中計算活多久的算式
    let oldest = inventors.sort(function(a, b) {
      return (a.passed - a.year) > (b.passed - b.year) ? -1 : 1
    })
    console.table(oldest)
    
  6. 去連結網站尋找 名字裡面有包含 'de' 的姓名:

    • 至連結打開 console 執行
    • 透過 querySelectorAll 抓到的值不是陣列所以沒有 map ,必須依靠 Array.from 來轉成陣列
    let category = document.querySelector('.mw-category')
        let links = Array.from(category.querySelectorAll('a'))
        let de = links
                    .map(link => link.textContent)
                    .filter(streetName => streetName.includes('de'))
    
  7. 從 people 的變數中透過 split 切開姓名並用 sort 排序活得長至短:

    let alphabetically = people.sort(function(a,b){
      let [alast, afirst] = a.split(', ')
      let [blast, bfirst] = b.split(', ')
      return alast > blast ? 1 : -1
    })
    console.table(alphabetically)
    
  8. 紀錄每個 data 中的物件共出現幾次:

    • 如果沒有這個物件,必須設為一、有的話每次讀到要加一
    let transportation = data.reduce(function(obj,content){
      if(!obj[content]) obj[content] = 1
      else obj[content] += 1
      return obj
    },{})
    console.table(transportation)
    

    同類型題目小試身手:

    Array.prototype.inspect = function() {
      console.log(this)
      return this
    }
    
    let students = [
      {name: "John Doe", age: 24},
      {name: "Mary Lee", age: 17},
      {name: "Bill Doe",  age: 2},
      {name: "Ash Lee",  age: 38},
      {name: "Ryu Doe",  age: 18},
    ]
    
    let result = 
      students.filter(({age}) => age >= 18)
              .map(({name}) => name.split(' ')[1])
              .inspect()
              .reduce((accu, name) => {
                if (accu[name]) {
                  accu[name] = accu[name] + 1
                } else {
                  accu[name] = 1
                }
                return accu
              }, {})
    
    console.log(result)
    

就大功告成啦!

JS - Final

  <script>
    // Get your shorts on - this is an array workout!
    // ## Array Cardio Day 1

    // Some data we can work with

    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'];

    // Array.prototype.filter()
    // 1. Filter the list of inventors for those who were born in the 1500's
    let fifteen = inventors.filter(function(inventor){
      return inventor.year >= 1500 && inventor.year < 1600
    })
    // console.table(fifteen)

    // Array.prototype.map()
    // 2. Give us an array of the inventors' first and last names
    let fullnames = inventors.map(function(inventor){
      return inventor.first + ' ' + inventor.last
    })
    // console.table(fullnames)

    // Array.prototype.sort()
    // 3. Sort the inventors by birthdate, oldest to youngest

    let ordered = inventors.sort(function(a, b){
      return a.year > b.year ? 1 : -1
    })
    // console.table(ordered)

    // Array.prototype.reduce()
    // 4. How many years did all the inventors live?

    let totalYears = inventors.reduce(function(total,inventor){
      return total + (inventor.passed - inventor.year)
    }, 0)
    // console.log(totalYears)

    // 5. Sort the inventors by years lived
    let oldest = inventors.sort(function(a, b) {
      return (a.passed - a.year) > (b.passed - b.year) ? -1 : 1
    })
    // console.table(oldest)

    // 6. create a list of Boulevards in Paris that contain 'de' anywhere in the name
    // https://en.wikipedia.org/wiki/Category:Boulevards_in_Paris

    // let category = document.querySelector('.mw-category')
    // let links = Array.from(category.querySelectorAll('a'))
    // let de = links
    //             .map(link => link.textContent)
    //             .filter(streetName => streetName.includes('de'))


    // 7. sort Exercise
    // Sort the people alphabetically by last name

    let alphabetically = people.sort(function(a,b){
      let [alast, afirst] = a.split(', ')
      let [blast, bfirst] = b.split(', ')
      return alast > blast ? 1 : -1
    })
    console.table(alphabetically)

    // 8. Reduce Exercise
    // Sum up the instances of each of these
    const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];

    let transportation = data.reduce(function(obj,content){
      if(!obj[content]) obj[content] = 1
      else obj[content] += 1
      return obj
    },{})
    console.table(transportation)
  </script>

本刊同步於個人網站:http://chestertang.site/
本次範例程式碼原作者來源:https://reurl.cc/9zZGYv


上一篇
新手村03 - CSS Variables
下一篇
新手村05 - Flex Panel Gallery
系列文
新手村-30 Day JS Coding Challenge30

尚未有邦友留言

立即登入留言