# 07-4. 배열내장 함수(map)

## 배열내장 함수

배열을 다룰 때 알고있으면 너무나 유용한 다양한 내장 함수들에 대하여 알아보겠습니다.

### map

`map` 은 배열 안의 각 원소를 변환 할 때 사용 되며, 이 과정에서 새로운 배열이 만들어집니다.

예를 들어서 다음과 같은 배열이 있다고 가정해봅시다.

```javascript
const array = [1, 2, 3, 4, 5, 6, 7, 8];
```

만약에 배열 안의 모든 숫자를 제곱해서 새로운 배열을 만들고 싶다면 어떻게 해야 할까요? \
map 함수를 사용하지 않고 우리가 지금까지 배운 지식들을 활용하면 다음과 같이 구현 할 수 있습니다.

```javascript
// ❌ Bad Code

const array = [1, 2, 3, 4, 5, 6, 7, 8];

// *1번 방법*
const squared = [];
for (let i = 0; i < array.length; i++) {
  squared.push(array[i] * array[i]);
}

// *2번 방법*  1번 방법보다 더 깔끔하게 작성이 가능하다.
const squared = [];
array.forEach(n => {
  squared.push(n * n);
});

// *3번 방법*  2번 방법보다 더 깔끔하게 작성이 가능하다.
const square = n => n * n;
const squared = array.map(square);


console.log(squared);
```

결과는 다음과 같습니다.

```javascript
// 결과)
[1, 4, 9, 16, 25, 36, 49, 64];
```

### map을 활용해서 다양한것을 해보자

```javascript
// ✅ Good Code

const items = [
    {
        id:1,
        text: 'hello'
    },
    
    {
        id:2,
        text: 'bye'
    }
]

const texts = items.map(item => item.text);
console.log(texts);  
```

```javascript
//결과) 
["text", "bye"]
```

## map 활용한 예시

```javascript
// ❌ Bad Code

const arrayText = Array.from(document.querySelectorAll('elemant'));
const jsonArray = new Array();
  arrayText.forEach((el, idx) => {
      const jsonObj = new Object();
      jsonObj.id = (idx+1);
      jsonObj.txt = el;
      jsonObj.link = el.childNodes[1].getAttribute('href');
      jsonArray.push(jsonObj)
  });

console.log(jsonArray)
```

```javascript
// ✅ Good Code

const arrayText = Array.from(document.querySelectorAll('elemant'));
const jsonArray = arrayText.map((el, idx) => {
    const jsonObj = new Object();
        jsonObj.id = (idx+1);
        jsonObj.txt = el;
        jsonObj.link = el.childNodes[1].getAttribute('href');
        return jsonObj;
    });

console.log(jsonArray);
```

![](/files/-MjClCbjkq59uEqo17V9)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://triplexlab.gitbook.io/vanilla-js/basics/07-array/07-3-map.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
