JS - Array method / TIL - 5

주지홍·2022년 1월 2일

TIL

목록 보기
9/25
post-thumbnail

Array method

arrow function을 가장 많이 사용할 때는 callback 함수로 사용할 때

map 메서드 : 배열을 반복해주는 메서드
callback 함수에서 return한 값으로 매(each) 요소를 수정해 준다.
map 메서드의 return 값은 수정된 값으로 다시 생성된 배열.

참고자료

JS Map Function

Array.Map()

const arr = [1, 2, 3];

const squares = arr.map(x => x * x);

const squares = arr.map(function (x) { 
  return x * x;
});

Array 타입의 데이터를 요소 갯수 만큼 반복
반복할 때마다 실행할 함수를 parameter로 전달
그러면 이 callback 함수에서 array의 요소를 인자(x)로 받음.
해당 요소를 수정하고 싶은대로 로직을 구현하고 return해주면,
해당 index의 요소가 return 된 값으로 치환

Array.forEach()

forEachfor 대신 사용하는 반복문

map 과의 큰 차이는 forEach 함수 자체가 return 하는 것도 아무것도 없다는 것

forEach 함수를 탈출하고 싶을 때 return 을 사용

map 은 요소가 수정된 새로운 배열이 return 되었다면,

forEach 는 아무것도 return 하는 것이 없다.

그래서 forEach 로 전달되는 callback 함수에서도 return하는 것이 없다.

forEach 는 단지 for 문 대신 사용하는 반복 method

let hasC = false;
let arr = ['a', 'b', 'c', 'd'];

arr.forEach(e1=> {
  if (e1 === 'c') {
    hasC = true;
    return;
  }
});

console.log(hasC); // hasC = true
  
let startWithNames = [];
let names = ['a', 'ab', 'cbb', 'ada'];

names.forEach(e1 => {   
  if (e1.startsWith('a')) {     
    startWithNames.push(e1);   
  } return names;
});

console.log(startWithNames); // ['a', 'ab', 'ada']

et idxOfC = -1;
let arr2 = ['a', 'b', 'c', 'd'];

arr.forEach((e1, idx) => {
  if (e1 === 'c') {
    idxOfC = idx;
    return;
  }
});

console.log(idxOfC); //2

문제

문제 1 : moreThan100 함수를 구현해 주세요.
숫자로 구성된 배열을 인자로 받습니다.
100 보다 크거나 같으면, true100 보다 작으면 false 로 요소를 변경하여, 새로운 배열을 return 해주세요.

nums(input)
[100, 9, 30, 7]

return[true, false, false, false]

const moreThan100 = nums => {
  return nums.map(i => {
    if (i >= 100) {
      return true;
    } else {
      return false;
    }
  })
};


문제 2 : formatDate 함수를 구현해 주세요.
날짜가 담긴 배열을 인자로 받습니다.
날짜의 data type은 string이며, 보내는 날짜 타입은 'YYYY-MM-DD' 입니다.
해당 날짜의 형식을 'YYYY년 MM월 DD일' 로 바꿔서, 새로운 배열을 return 해주세요.

dates(input)
['2019-03-21', '2019-04-21', '2019-05-21']

return['2019년 03월 21일', '2019년 04월 21일', '2019년 05월 21일']

const formatDate = dates => {
  return dates.map(el => {
    const line = el.indexOf('-');
    const year = el.slice(0, line);
    const month =el.slice(line+1, line+3);
    const date =el.slice(line+4, el.length);
    const result = `${year}${month}${date}`;
    
    return result;
  })
};
profile
오늘도 내일도 끊임없는 싸움

0개의 댓글