---
# System prepended metadata

title: JS30 Day4
tags: [JS 30]

---

# 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/)

---

### 感謝收聽，下回再見
