[Javascript] 프로그래머스 - 배열 두 배 만들기(map)

seoyeon·2023년 4월 15일
2

Javascript 공부하기

목록 보기
14/20
post-thumbnail

프로그래머스 코딩테스트 입문 문제📝

정수 배열 numbers가 매개변수로 주어집니다. numbers의 각 원소에 두배한 원소를 가진 배열을 return하도록 solution 함수를 완성해주세요.

✔ 제한사항

  • -10,000 ≤ numbers의 원소 ≤ 10,000
  • 1 ≤ numbers의 길이 ≤ 1,000
function solution(numbers) {
	var answer = numbers.map(num => num * 2);
  	return answer;
}

해당 문제는 .map() 메서드를 쓰면 간단하게 해결할 수 있다😎

1. map()

map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환한다. ❗map() 또한 원본 배열은 바뀌지 않는다❗

📌 구문

arr.map(callback(currentValue[, index[, array]])[, thisArg])

매개변수

callback
새로운 배열 요소를 생성하는 함수. 다음 세 가지 인수를 가집니다.

currentValue
처리할 현재 요소.

index Optional
처리할 현재 요소의 인덱스.

array Optional
map()을 호출한 배열

thisArg Optional
callback 을 실행할 때 this 로 사용되는 값.

사용법

const arr = [1, 4, 9, 16];

const map = arr.map(x => x * 2);
console.log(map) // [2, 8, 18, 32]

map 함수를 사용하여 배열의 모든 값에 2를 곱한 새로운 배열을 생성하였다.

map 함수는 Object(객체)타입도 컨트롤 할 수 있다.

const students = [
  {key:1, name:"Jane"},
  {key:2, name:"Sandy"},
  {key:3, name:"Tom"},
  {key:4, name:"Sara"}
];

const studentName = students.map(student => student.name);
console.log(studentName) // ['Jane','Sandy','Tom','Sara']

students의 name만 가져와서 새로운 배열을 생성하였다.


📄 참고자료

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/map

0개의 댓글