JS30 Day4

Array Cardio Day

tags: JS 30

by Angelina


Array


Data

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?

  1. Sort the inventors by years lived
  2. create a list of Boulevards in Paris that contain 'de' anywhere in the name
  3. sort Exercise:Sort the people alphabetically by last name
  4. 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)

const fifteen = inventors.filter(function(inventor) { if(inventor.year >= 1500 && inventor.year <= 1599) { return true } }) console.log(fifteen) console.table(fifteen)


  • 利用 arrow function 箭頭函式簡化
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)

const fullNames = inventors.map(inventor => inventor.first+ '' + inventor.last)
  • template strings 樣板字串
const fullNames = inventors.map(inventor => `${inventor.first} ${inventor.last}`); console.log(fullNames);


  • 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 也是不換位置

const ordered = inventors.sort(function(a, b) { if(a.year > b.year) { return 1; } else { return -1; } });
  • 利用 Ternary Operator 三元運算子簡化
const ordered = inventors.sort((a, b) => a.year > b.year ? 1 : -1); console.table(ordered);


  • a 為第一個人,b 為第二個人,year 的數字越小,年齡越大
  • return 1 會換位置,-1 不會換位置,0 相等不換位置
  • 當 a.year 的數字 比 b.year 的數字大的時候,表示 a 比 b 小,回傳 1 就要換位置了

第四題

How many years did all the inventors live?

  • 加總 inventors 的壽命
  • 迴圈解法:
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() 解法:
const totalYears = inventors.reduce((total, inventor) => { return total + (inventor.passed - inventor.year); }, 0); console.log(totalYears);


  • 以前都會用迴圈,宣告變數,從 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()

(未處理相等情況)

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)


  • 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 元素

  • 找到要抓的內容

const category = document.querySelector('.mw-category');


const category = document.querySelector('.mw-category'); const links = category.querySelectorAll('a');


  • 從每個 link 裡面拿到 name
const category = document.querySelector('.mw-category'); const links = category.querySelectorAll('a'); const de = links.map(link => link.textContent);

  • querySelectorAll 方法回傳一個類似陣列的物件稱為 Node List。這些資料結構簡稱為「類陣列」,因為他們和陣列很相似,但是不能使用陣列的方法像是 map 和 forEach

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)
  • 重整後再丟一次程式碼

牛刀小試

下列何者是用於過濾?

( A ) file
( B ) filled
( C ) filter
( D ) full


  • filter() 將包含 de 的過濾出來
  • 選取網頁中含有de的的街道,使用.includes('de')
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'));


有時間再看:


第七題

sort Exercise:Sort the people alphabetically by last name

  • 對 people 陣列的姓,進行排序
  • split() 方法是依據給的內容拆分 string 成 array

  • sort() 排序
const alpha = people.sort((lastOne, nextOne) => { console.log(lastOne, nextOne) });


  • split() 內容拆分 string 成 array
const alpha = people.sort((lastOne, nextOne) => { const parts = lastOne.split(', ') console.log(parts) });


  • Destructuring assignment 解構賦值語法,可以把陣列或物件中的資料解開擷取成為獨立變數
const alpha = people.sort((lastOne, nextOne) => { const [last, first] = lastOne.split(', '); console.log(last, first) });


  • a, b 比較,依照 lastname 的字母順序排列
const alpha = people.sort((lastOne, nextOne) => { const [aLast, aFirst] = lastOne.split(', '); const [bLast, bFirst] = nextOne.split(', '); return aLast > bLast ? 1 : -1; }); console.log(alpha);


第八題

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

  • 初始值位置放上空物件{},代表回傳的是一個物件
const transportation = data.reduce((obj, item) => { if (!obj[item]) { obj[item] = 0; } obj[item]++; return obj; }, {}); console.log(transportation)


參考資料 / 資源


感謝收聽,下回再見

Select a repo