陣列方法:map()、filter()、reduce()

map()、filter()、reduce(),React很常用到,一定要記得。

學生名單陣列練習範例:

const students = [
  {
    name: 'Abby',
    age: 17,
    gender: 'female',
  },
  {
    name: 'Betty',
    age: 18,
    gender: 'female',
  },
  {
    name: 'Charlie',
    age: 16,
    gender: 'male',
  },
  {
    name: 'David',
    age: 19,
    gender: 'male',
  },
  {
    name: 'Emily',
    age: 18,
    gender: 'female',
  },
];

// 1請使用 map 回傳一個只有 name 字串的陣列
// expect ["Abby","Betty","Charlie","David","Emily"]
console.log(students.map((s) => s.name));


// 2同上,但我想根據 gender 加入前綴 "Mr." 與 "Miss",例 ["Miss Betty", "Mr. Charlie"]
// expect ["Miss Abby","Miss Betty","Mr. Charlie","Mr. David","Miss Emily"]
const getTitle = (gender) => (gender === "mail" ? "Mr." : "Miss");
console.log(students.map((s) => `${getTitle(s.gender)} ${s.name}`));


// 3請使用 filter 回傳 gender 為 female 而且 age 已滿 18 歲的 students 物件
// expect [{"name":"Betty","age":18,"gender":"female"},{"name":"Emily","age":18,"gender":"female"}]
console.log(students.filter((s) => s.gender === "female" && s.age >= 18));


// 4請使用 reduce 計算平均年齡
// expect 17.6
console.log(students.reduce((age, s) => age + s.age / students.length, 0));

發表迴響