17. Sort Without Articles

💡 주어진 배열을 관사(A, An, The)를 제외한 알파벳 순으로 정렬해보자!

연재 WesBos Vanilla JS 30 Challenge 14/21

전체 21편 보기
  1. 01. Drum kit
  2. 02. Clock
  3. 03. CSS Variables 조절하기
  4. 04. Array 메서드 활용 1
  5. 05. Flex Panel
  6. 06. 검색 자동완성 기능 구현
  7. 07. Array 메서드 활용 2
  8. 09. 개발자 도구 활용
  9. 10. Hold Shift to check the box
  10. 11. Custom Video Player
  11. 12. Key Sequence Detection
  12. 13. 스크롤 시 이미지 슬라이드
  13. 14. 배열&객체의 복사와 참조
  14. 17. Sort Without Articles
  15. 22. Following Highlight
  16. 24. Sticky Nav
  17. 25. 이벤트 캡쳐와 버블링
  18. 26. 동적인 드롭다운 Nav
  19. 27. Click And Drag
  20. 29. CountDown Timer
  21. 30. 두더지 뚝배기
목차

💡 주어진 배열을 관사(A, An, The)를 제외한 알파벳 순으로 정렬해보자!

로직 #

  1. 관사를 제거한채로 반환해주는 함수 생성
  2. 관사를 제거한 요소들을 sort()로 알파벳 순으로 정렬
  3. 정렬된 요소들을 화면에 나타내기

코딩 과정 #

1. 관사 제거 함수 생성 #

javascript
function strip(bandName) {
  return bandName.replace(/^(a |the |an )/i, '').trim()
}

replace() 메서드로 관사를 공백으로 바꾼 뒤 trim()메서드로 좌우 공백을 제거한다.

2. sort()로 정렬 #

javascript
const bands = [
  'The Plot in You',
  'The Devil Wears Prada',
  'Pierce the Veil',
  'Norma Jean',
  'The Bled',
  'Say Anything',
  'The Midway State',
  'We Came as Romans',
  'Counterparts',
  'Oh, Sleeper',
  'A Skylit Drive',
  'Anywhere But Here',
  'An Old Dog',
]

const sortedBands = bands.sort((a, b) => (strip(a) > strip(b) ? 1 : -1))

strip()으로 관사를 제거한 채로 반환된 요소들을 sort() 메서드로 알파벳 순으로 정렬한다.

3. 화면에 나타내기 #

javascript
document.querySelector('#bands').innerHTML = sortedBands
  .map(band => `<li>${band}</li>`)
  .join('')

정렬된 요소들을 각각 <li>로 매핑하여 화면에 나타낸다

최종 완성 코드 #

javascript
const bands = [
  'The Plot in You',
  'The Devil Wears Prada',
  'Pierce the Veil',
  'Norma Jean',
  'The Bled',
  'Say Anything',
  'The Midway State',
  'We Came as Romans',
  'Counterparts',
  'Oh, Sleeper',
  'A Skylit Drive',
  'Anywhere But Here',
  'An Old Dog',
]

function strip(bandName) {
  return bandName.replace(/^(a |the |an )/i, '').trim()
}

const sortedBands = bands.sort((a, b) => (strip(a) > strip(b) ? 1 : -1))

document.querySelector('#bands').innerHTML = sortedBands
  .map(band => `<li>${band}</li>`)
  .join('')