[Next js]가장 오래된 날짜 구하기

임보라·2024년 10월 27일

Next.js

목록 보기
14/23

날짜를 가지고있는 객체를 담은 배열에서 가장 오래된 날짜를 추출해야한다.

stampData_

stampData


시도1_(X)

  // 가장 오래된 날짜 구하기
  const oldestDate = stampData.map((list) => {
    return list.created_at.reduce((oldest, current) => {
      return current < oldest ? current : oldest;
    });
  });
  console.log('oldestDate', oldestDate);

문제점)

  • TypeError: list.created_at.reduce is not a function
  • list.created_at.reduce 이게 없다고 나옴

원인)

  • 이유는 스트링이라 비교불가

시도2_(O)

  // 가장 오래된 날짜 구하기
  const oldestDate =
    stampData.reduce((oldest, current) => {
      const oldestDate = new Date(oldest.created_at); //비교대상날짜
      const currentDate = new Date(current.created_at); //비교할 기준점날짜
      return currentDate < oldestDate ? current : oldest;
    });
  • reduce는 기존에 map을 따로 사용안해도 reduce자체에서 순회하며 값을 비교하기때문에 map을 제거
  • 문자열로 저장된 날짜를 값 비교를 위해 new Date 로 새로 변수에 담아준다.
  • 날짜를 기준으로 삼항연산자 :
    currentDate < oldestDate
    기준점(currentDate)이 oldestDate보다 오래된날짜라면
    ccurrent : oldest
    true : current가 가장 오래된 날짜
    false : oldest가 가장 오래된 날짜

참고자료
mdn) Array.prototype.reduce()
reduce 함수란?

0개의 댓글