목차
0. map 이란
: 기존 배열을 변형(각 요소를 가공)해서 새로운 배열을 반환한다.
: 기존 배열은 변경되지 않는다. (불변성 유지)
: 콜백 함수를 인자로 받고, 원본 배열의 각 요소를 순회하면서 변형된 값을 새 배열에 저장한다.
- 숫자 변환, 데이터 매핑 등, 배열의 각 요소를 변형해야 하는 경우 유용하다.
※ reduce() 는 배열을 순회하며 하나의 최종 값을 반환할 때 쓰인다. (합계, 평균, 객체 변환 등)
※ forEach() 는 배열을 단순히 순회하고 작업을 수행할 뿐, 반환값은 없다.
const newArray = oldArray.map((element, index, array) => {
return 변환된_값;
});
element - 현재 배열 요소
index - 현재 요소의 인덱스 (선택사항)
array - map()을 호출한 원본 배열 (선택사항)
예시 1) 모든 숫자 2배로 만들기
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(num => num ** 2);
console.log(squaredNumbers); // [1, 4, 9, 16, 25] (각 요소를 제곱한 새 배열)
console.log(numbers); // [1, 2, 3, 4, 5] (원본 배열은 그대로 유지됨)
예시 2) 문자열을 대문자로 변환하기
const words = ['hell0', 'world', 'javascript'];
const upperCaseWords = words.map(word => word.toUpperCase());
console.log(upperCaseWords); // ['HELLO', 'WORLD', 'JAVASCRIPT']
예시 3) 객체 배열에서 특정 속성 값만 추출하기
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
];
const names = users.map(user => user.name);
console.log(names); // ['Alice', 'Bob', 'Charlie']
예시 4) 배열 요소를 특정 형식의 문자열로 변환
const products = [
{ name: 'Laptop', price: 1000 },
{ name: 'Phone', price: 500 },
{ name: 'Tablet', price: 700 }
];
const productDescriptions = products.map(product => `${product.name} costs $${product.price}`);
console.log(productDescriptions);
// ['Laptop costs $1000', 'Phone costs $500', 'Tablet costs $700']
예시 5) index 활용
const fruits = ['apple', 'banana', 'cherry'];
const numberedFruits = fruits.map((fruit, index) => {
return `${index + 1}. ${fruit}`;
});
console.log(numberedFruits); // ['1. apple', '2. banana', '3. cherry']
예시 6) array 활용해서 상대 평가하기
const scores = [90, 85, 78, 92, 88];
const relativeScores = scores.map((score, _, array) => {
const highest = Math.max(...array); // 배열에서 가장 높은 점수 찾기
return `Score: ${score} (${((score / highest) * 100).toFixed(2)}%)`;
});
console.log(relativeScores);
/*
[
'Score: 90 (97.83%)',
'Score: 85 (92.39%)',
'Score: 78 (84.78%)',
'Score: 92 (100.00%)',
'Score: 88 (95.65%)'
]
*/
예시 7) 이중 map() - 내부 배열 (배열 > 객체 > 배열) 변형
객체를 변경할 때는 원본을 유지하기 위해 { ...user } 처럼 복사하는 게 좋다.
const users = [
{
name: "Alice",
items: ["apple", "banana"]
},
{
name: "Bob",
items: ["pen", "notebook"]
}
];
const updatedUsers = users.map(user => {
return {
...user, // 기존 객체를 유지하면서
items: user.items.map(item => item + "!") // 각 아이템에 "!" 추가
};
});
console.log(updatedUsers);
/*
[
{ name: 'Alice', items: ['apple!', 'banana!'] },
{ name: 'Bob', items: ['pen!', 'notebook!'] }
]
*/
예시 8) 이중 map() - 다차원 배열 (행렬) 변형
const matrix = [
[1, 2, 3],
[4, 5, 6]
];
const doubledMatrix = matrix.map(row =>
row.map(num => num * 2) // 각 요소를 2배로 변환
);
console.log(doubledMatrix);
/*
[
[2, 4, 6],
[8, 10, 12]
]
*/
0. map 이란
: 기존 배열을 변형(각 요소를 가공)해서 새로운 배열을 반환한다.
: 기존 배열은 변경되지 않는다. (불변성 유지)
: 콜백 함수를 인자로 받고, 원본 배열의 각 요소를 순회하면서 변형된 값을 새 배열에 저장한다.
- 숫자 변환, 데이터 매핑 등, 배열의 각 요소를 변형해야 하는 경우 유용하다.
※ reduce() 는 배열을 순회하며 하나의 최종 값을 반환할 때 쓰인다. (합계, 평균, 객체 변환 등)
※ forEach() 는 배열을 단순히 순회하고 작업을 수행할 뿐, 반환값은 없다.
const newArray = oldArray.map((element, index, array) => {
return 변환된_값;
});
element - 현재 배열 요소
index - 현재 요소의 인덱스 (선택사항)
array - map()을 호출한 원본 배열 (선택사항)
예시 1) 모든 숫자 2배로 만들기
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(num => num ** 2);
console.log(squaredNumbers); // [1, 4, 9, 16, 25] (각 요소를 제곱한 새 배열)
console.log(numbers); // [1, 2, 3, 4, 5] (원본 배열은 그대로 유지됨)
예시 2) 문자열을 대문자로 변환하기
const words = ['hell0', 'world', 'javascript'];
const upperCaseWords = words.map(word => word.toUpperCase());
console.log(upperCaseWords); // ['HELLO', 'WORLD', 'JAVASCRIPT']
예시 3) 객체 배열에서 특정 속성 값만 추출하기
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
];
const names = users.map(user => user.name);
console.log(names); // ['Alice', 'Bob', 'Charlie']
예시 4) 배열 요소를 특정 형식의 문자열로 변환
const products = [
{ name: 'Laptop', price: 1000 },
{ name: 'Phone', price: 500 },
{ name: 'Tablet', price: 700 }
];
const productDescriptions = products.map(product => `${product.name} costs $${product.price}`);
console.log(productDescriptions);
// ['Laptop costs $1000', 'Phone costs $500', 'Tablet costs $700']
예시 5) index 활용
const fruits = ['apple', 'banana', 'cherry'];
const numberedFruits = fruits.map((fruit, index) => {
return `${index + 1}. ${fruit}`;
});
console.log(numberedFruits); // ['1. apple', '2. banana', '3. cherry']
예시 6) array 활용해서 상대 평가하기
const scores = [90, 85, 78, 92, 88];
const relativeScores = scores.map((score, _, array) => {
const highest = Math.max(...array); // 배열에서 가장 높은 점수 찾기
return `Score: ${score} (${((score / highest) * 100).toFixed(2)}%)`;
});
console.log(relativeScores);
/*
[
'Score: 90 (97.83%)',
'Score: 85 (92.39%)',
'Score: 78 (84.78%)',
'Score: 92 (100.00%)',
'Score: 88 (95.65%)'
]
*/
예시 7) 이중 map() - 내부 배열 (배열 > 객체 > 배열) 변형
객체를 변경할 때는 원본을 유지하기 위해 { ...user } 처럼 복사하는 게 좋다.
const users = [
{
name: "Alice",
items: ["apple", "banana"]
},
{
name: "Bob",
items: ["pen", "notebook"]
}
];
const updatedUsers = users.map(user => {
return {
...user, // 기존 객체를 유지하면서
items: user.items.map(item => item + "!") // 각 아이템에 "!" 추가
};
});
console.log(updatedUsers);
/*
[
{ name: 'Alice', items: ['apple!', 'banana!'] },
{ name: 'Bob', items: ['pen!', 'notebook!'] }
]
*/
예시 8) 이중 map() - 다차원 배열 (행렬) 변형
const matrix = [
[1, 2, 3],
[4, 5, 6]
];
const doubledMatrix = matrix.map(row =>
row.map(num => num * 2) // 각 요소를 2배로 변환
);
console.log(doubledMatrix);
/*
[
[2, 4, 6],
[8, 10, 12]
]
*/