javascript/javascript30

[javascript30]Sorting Band Names without articles

소영 2021. 7. 21. 15:58
Sorting Band Names without articles

sort메서드로 관사(an,the,a)를 뺀 스펠링을 오름차순으로 정렬한다.

 

1. 관사들을 빼기 위해 대체 메서드(.replace)를 사용하기

2. 관사들을 선택하기 위해 정규식을 사용하기

3.sort메서드 활용법을 알기

4.map으로 Dom에 배열 정렬하기

 

코드
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Sort Without Articles</title>
</head>
<body>

  <style>
    body {
      margin: 0;
      font-family: sans-serif;
      background: url("https://source.unsplash.com/nDqA4d5NL0k/2000x2000");
      background-size: cover;
      display: flex;
      align-items: center;
      min-height: 100vh;
    }

    #bands {
      list-style: inside square;
      font-size: 20px;
      background: white;
      width: 500px;
      margin: auto;
      padding: 0;
      box-shadow: 0 0 0 20px rgba(0, 0, 0, 0.05);
    }
    
    #bands li {
      border-bottom: 1px solid #efefef;
      padding: 20px;
    }
    
    #bands li:last-child {
      border-bottom: 0;
    }

    a {
      color: #ffc600;
      text-decoration: none;
    }

  </style>

  <ul id="bands"></ul>

<script>
  //관사들을 빼고 오름차순으로 정렬하기
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();// a와 the와 an(관사들)을 빈칸으로 대체, .trim() 문자열 좌우에서 공백 제거하는 메서드
}

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

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

console.log(sortedBands);

</script>

</body>
</html>
알게된 문법
.replace([변경될 문자열],[변경할 문자열])

어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환하는 메서드

 

.trim()

문자열 좌우에서 공백 제거하는 메서드

.sort((a,b)=>a>b?1:-1);

sort를 이렇게 작성할 경우 오름차순으로 배열됨