객체의 시간 순으로 배열 정렬하기 (+과제 제출 확인)

김민아·2022년 9월 20일
0

📍 코드스테이츠 제출한 과제 확인하기

npx codestates-assignment-manager login

record를 timestamp 날짜 기준으로 array.sort()로 정렬하기

const record = [
  {
    name: 'fe-sprint-react-twittler-state-props',
    timestamp: '2022-08-02T14:37:15.141Z'
  },
  {
    name: 'fe-sprint-react-twittler-state-props',
    timestamp: '2022-08-03T02:23:26.496Z'
  },
  {
    name: 'fe-sprint-react-twittler-state-props',
    timestamp: '2022-08-03T10:36:50.156Z'
  },
  {
    name: 'fe-sprint-beesbeesbees',
    timestamp: '2022-07-25T05:49:43.405Z'
  },
  // ... 이하 생략
]

프로젝트 이름은 임의로 설정해 두었다. 객체는 시간에 상관없이 정렬이 되어 있어서 timestamp를 기준으로 정렬한다. 생각보다 간단하게 날짜를 비교할 수 있다.

날짜 비교하기

const d1 = new Date('2022-07-25T05:49:43.405Z');
const d2 = new Date('2022-07-30T05:49:43.405Z');

console.log(d1 >= d2); // false
console.log(d1 <= d2); // true

적용해보면 이런 식으로 작성이 될 수 있다.
시간을 기준으로 오름차순 정렬이 된 것을 확인할 수 있다.

// 오름차순 
record.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp))
const record = [
  {
    name: 'fe-sprint-cli-practice',
    timestamp: '2022-07-06T07:01:14.330Z'
  },
  {
    name: 'fe-sprint-calculator',
    timestamp: '2022-07-06T07:50:17.412Z'
  },
  {
    name: 'fe-sprint-javascript-koans',
    timestamp: '2022-07-13T04:33:26.250Z'
  },
  // ... 이하 생략
]

npx 작동 방식이 궁금하다. 로그인 정보를 알고 있으면 과제 제출을 확인할 수 있는 페이지를 만들 수도 있겠다. 🧐

0개의 댓글