Day4: Array Cardio Day 1 == ###### tags: `JS30` `array` Data ```javascript! 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 } ]; ``` ## <font color="#3733FF">filter</font> Practice:Filter the list of inventors for those who were born in the 1500's #### function ```javascript! const fifteen = inventors.filter(function(inventor) { if (inventor.year >= 1500 && inventor.year < 1600 ) { return true } }) ``` #### arrow function ```javascript! const fifteen = inventors.filter(inventor => inventor.year >= 1500 && inventor.year < 1600) ``` use console.table ![](https://i.imgur.com/i4IKC9w.png =80%x) ## <font color="#3733FF">map</font> Practice:Give us an array of the inventor first and last names :::warning map will always return same amount of item as you give it ::: #### function ```javascript! const fullName = inventors.map(function(inventor) { return inventor.first + ' ' + inventor.last }) ``` #### arrow function ```javascript! const fullName = inventors.map(inventor => `${inventor.first} ${inventor.last}`) ``` console.log(fullName) ![](https://i.imgur.com/u6ZjCTD.png =80%x) ## <font color="#3733FF">sort</font> Practice:Sort the inventors by birthdate, oldest to youngest :::warning 回傳 1 代表: 前面的數字大於後面的數字, b 放 a 前面 (遞減) 回傳 -1 代表: 前面的數字小於後面的數字, a 放 b 前面 (遞增) 回傳 0 代表: 前面的數字等於後面的數字,所以不變 想要升序排序(由小到大),可以使用 return a - b 想要降序排序(由大到小),可以使用 return b - a ::: #### function ```javascript! const ordered = inventors.sort(function(a,b) { if ( a.year > b.year) { return 1 } else { return -1 } }) ``` #### arrow function + Ternary Operator ```javascript! const ordered = inventors.sort((a,b) => a.year > b.year ? 1 : -1) ``` use console.table ![](https://i.imgur.com/qh9DrTm.png =80%x) --- Practice:Sort the inventors by years lived #### function ```javascript! const oldest = inventors.sort(function(a,b) { const lastGuy = a.passed - a.year const nextGuy = b.passed - b.year if (lastGuy > nextGuy) { return -1 } else { return 1 } }) ``` #### Ternary Operator ```javascript! const oldest = inventors.sort(function(a,b) { const lastGuy = a.passed - a.year const nextGuy = b.passed - b.year return lastGuy > nextGuy ? -1 : 1 }) ``` use console.table ![](https://i.imgur.com/BknErWX.png =80%x) ## <font color="#3733FF">reduce</font> How many years did all the inventors live? old way ```javascript! var totalYears = 0 for (var i = 0; i < inventors.length; i++) { totalYears += inventors[i].year } ``` :::warning reduce is much cleaner way ::: #### function ```javascript! const totalYears = inventors.reduce(function(total,inventor) { return total + (inventor.passed - inventor.year) },0) ``` #### arrow function ```javascript! const totalYears = inventors.reduce((total,inventor) => { return total + (inventor.passed - inventor.year) },0) ``` ### <font color="#3733FF">Sum up the instances of each of these</font> data ```javascript! const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck', 'pogostick']; ``` 建立一個物件,將 data 轉換為物件,存到變數 transportation,判斷物件 obj 中是否已經有 這個item 的key,如果沒有就加入item並設定為 0; 如果有就將數量加一 ```javascript! const transportation = data.reduce(function(obj, item) { if (!obj[item]) { obj[item] = 0 } obj[item]++ return obj //start with a blank object }, {}) ``` console.log(transportation) ``` {car: 5, truck: 3, bike: 2, walk: 2, van: 2, …} bike: 2 car: 5 pogostick: 1 truck: 3 van: 2 walk: 2 ``` --- ## Exercise ### <font color="#3733FF">create a list of Boulevards in Paris that contain 'de' anywhere in the name</font> [URL](https://en.wikipedia.org/wiki/Category:Boulevards_in_Paris) :::warning querySelector return a node list NodeLists 雖然看起來很像陣列,但我們只能「查看」它的內容,而不能使用 pop 或 push 去修改內容 ::: #### wrong way ```javascript! const category = document.querySelector('.mw-category') //call querySelector against any existing DOM to look inside of DOM element const links = category.querySelectorAll('a') const de = links.map(link => link.textContent) ``` 使用querySelector 拿到的資料是array-like,可以使用forEach,不能使用map,除非轉成真的陣列 got error message ![](https://i.imgur.com/ZPIrpIu.png) check NodeList prototype ![](https://i.imgur.com/dijmVuR.png =60%x) #### right way use `Array.from` can convert nodeList into an array ```javascript! const category = document.querySelector('.mw-category') //call querySelector against any existing DOM to look inside of DOM element const links = Array.from(category.querySelectorAll('a')) const de = links .map(link => link.textContent) .filter(streetName => streetName.includes('de')) ``` use ES6 spread to create an array ```javascript! const links = [...category.querySelectorAll('a')] ``` ![](https://i.imgur.com/evrwq4o.png) ### <font color="#3733FF">Sort the people alphabetically by last name</font> 將 people 陣列中的名字按照姓氏的字母順序進行排序 data ```javascript! const people = [ 'Bernhard, Sandra', 'Bethea, Erin', 'Becker, Carl', 'Bentsen, Lloyd', 'Beckett, Samuel', 'Blake, William', 'Berger, Ric', 'Beddoes, Mick', 'Beethoven, Ludwig', 'Belloc, Hilaire', 'Begin, Menachem', 'Bellow, Saul', 'Benchley, Robert', 'Blair, Robert', 'Benenson, Peter', 'Benjamin, Walter', 'Berlin, Irving', 'Benn, Tony', 'Benson, Leana', 'Bent, Silas', 'Berle, Milton', 'Berry, Halle', 'Biko, Steve', 'Beck, Glenn', 'Bergman, Ingmar', 'Black, Elk', 'Berio, Luciano', 'Berne, Eric', 'Berra, Yogi', 'Berry, Wendell', 'Bevan, Aneurin', 'Ben-Gurion, David', 'Bevel, Ken', 'Biden, Joseph', 'Bennington, Chester', 'Bierce, Ambrose', 'Billings, Josh', 'Birrell, Augustine', 'Blair, Tony', 'Beecher, Henry', 'Biondo, Frank' ]; ``` #### function ```javascript! const alpha = people.sort(function(lastOne, nextOne) { //destructure const [aLast, aFirst] = lastOne.split(',') const [bLast, bFirst] = nextOne.split(',') return aLast > bLast ? 1 : -1 }) ``` #### arrow function ```javascript! const alpha = people.sort((lastOne, nextOne) => { //destructure const [aLast, aFirst] = lastOne.split(',') const [bLast, bFirst] = nextOne.split(',') return aLast > bLast ? 1 : -1 }) ```