← Snippets

Filter Map

 type Student = {
  name: string
  age: number
}

const students: Student[] = [
  { name: 'Thanh', age: 10 },
  { name: 'Huy', age: 11 },
  { name: 'Hai', age: 14 },
  { name: 'Phong', age: 15 }
]
 

Get list name of student over 12 using .reduce()

 const result = students.reduce((prev, student) => {
  if (student.age > 12) {
    return [...prev, student.name]
  }

  return prev;
}, [] as string[])
 

Get list name of student over 12 using .flatMap()

 const result = students.flatMap(student => {
  if (student.age > 12) {
    return student.name
  }

  return []
})
 

Result

 console.log(result)
/* Result is:
[
  { name: 'Hai', age: 14 },
  { name: 'Phong', age: 15 }
]
*/