TypeScript/TypeScript - 기초부터 실전까지

20. map() - 특정 배열을 변환하여 새로운 배열을 만든는 함수

DEV-Front 2023. 10. 14. 17:25
반응형
  displayListByName(): string[] {
    // map - 기존 배열을 변환해서 새로운 배열을 만든다.
    // 아래 코드는 contact 배열의 name으로만 새로운 배열을 만든 코드다
    return this.contacts.map(contact => contact.name);
  }

  displayListByAddress(): string[] {
    return this.contacts.map(contact => contact.address);
  }


let heroes = [
  { name: 'Tony', age: 30 },
  { name: 'Captain', age: 100 },
];

heroes.map(function (hero) {
  return hero.name;
});

예) herose 배열에서 name만 뽑아서 새로운 배열을 만들고 싶은 경우에 map을 사용한다.

반응형