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

배열내장 함수

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

map

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

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

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

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

// ❌ 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);

결과는 다음과 같습니다.

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

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

// ✅ Good Code

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

const texts = items.map(item => item.text);
console.log(texts);  
//결과) 
["text", "bye"]

map 활용한 예시

// ❌ 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)
// ✅ 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);

Last updated