[筆記][JS30天-Day04] Array Cardio Day1

JS_30_Days

實做:Array方法操作

學習重點
  • Array方法操作:sort , map , filter ,reduce
  • Array.from 轉成陣列

解說

請把程式碼貼到瀏覽器console查看結果


順道提 console.table( );
在Chrome console 下看會變成下圖這樣

變成表格格式了!Cool ~


1
2
3
4
5
6
7
8
9
10
11
12
13
14
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 }
];
  • filter
    callback function 返回 true 即保留該元素
1
2
3
4
5
const fifteen = inventors.filter(
//如果出生年份介於1500~1599就保留
inventor => inventor.year >= 1500 && inventor.year < 1600
);
console.table(fifteen);
  • map
    callback function 處理後返回新陣列
1
2
3
4
const fullName = inventors.map(
inventor => inventor.first + ' ' + inventor.last
);
console.table(fullName);
  • sort
    預設依照Unicode進行排序
1
2
3
var scores = [1, 10, 21, 2]; 
scores.sort();
// [1, 10, 2, 21] ,10 會在 2 之前要特別注意

也可以自訂compare function,若a>b 大於0,b會排在a之前

1
2
const ordered = inventors.sort( (a, b) => (a > b) ? 1 : -1 );
console.table(ordered);

排序活的年數lol

1
inventors.sort( (a, b) => a.passed - a.year - (b.passed - b.year) );
  • reduce
    由左到右將所有元素做累加,並返回最終值
1
2
3
4
[0,1,2,3,4].reduce(function(preVal, lastVal, index, array){
return preVal + lastVal;
});
//10

後面可以多一個參數當作初始值

1
2
3
4
[0,1,2,3,4].reduce(function(preVal, lastVal, index, array){
return preVal + lastVal;
}, 10);
//20

統計重複的值有幾個

1
2
3
4
5
6
7
8
9
const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];
const reduce = data.reduce( (obj, item) => {
if( !obj[item] ) { //若預設物件沒有就新增一個,並給初始為0
obj[item] = 0;
}
obj[item]++;
return obj;
}, {}); //預設給一個空物件
console.log(reduce);

最後結合 map 與 filter 在下面網站找出所有含有 de 的字眼
https://en.wikipedia.org/wiki/Category:Boulevards_in_Paris

1
2
3
4
const aElement = Array.from(document.querySelectorAll('.mw-category a'))
let list = aElement.map(item => item.textContent)
.filter(item => item.includes('de'))
console.log(list);

querySelectorAll()不是陣列所以沒有Array方法,可以使用Array.from轉成陣列格式,
或者使用ES6解構語法,

1
[...document.querySelectorAll('.mw-category a')]; //注意要加上[ ]

ES5用法則是

1
[].slice.call(document.querySelectorAll('.mw-category a'));