프로그래밍 언어/JavaScript

[JS] 문자열 정렬하기, (localeCompare())

s워니얌 2023. 2. 8. 17:12

 

object에 저장되어 있는 문자들을 영순, 가나다 순으로 정리하려고 한다. 그럴때 짧은 코드로 쉽게 사용할 수 있는 방법이 있다.  

 

📑 localeCompare 이란?

 

기준 문자열과 비교했을 때 대상 문자열이 정렬상 전에 오는지, 후에 오는지 혹은  같은 순서에 배치되는지를 알려주는 숫자를 리턴한다. 즉 음수, 0, 양수를 반환한다는 의미이다. 

 

아래와 같은 데이터가 있을때 이 title을 기준으로 문자순으로 정렬하려고 한다.

export default[{
    id : 0,
    title: "Sinrim station 30 meters away",
    image: "https://codingapple1.github.io/vue/room0.jpg",
    content: "18년 신축공사한 남향 원룸 ☀️, 공기청정기 제공",
    price: 340000
    },
    {
    id : 1,
    title: "Changdong Aurora Bedroom(Queen-size)",
    image: "https://codingapple1.github.io/vue/room1.jpg",
    content: "침실만 따로 있는 공용 셰어하우스입니다. 최대 2인 가능",
    price: 450000
    },
    {
    id : 2,
    title: "Geumsan Apartment Flat",
    image: "https://codingapple1.github.io/vue/room2.jpg",
    content: "금산오거리 역세권 아파트입니다. 애완동물 불가능 ?",
    price: 780000
    },
    {
    id : 3,
    title: "Double styled beds Studio Apt",
    image: "https://codingapple1.github.io/vue/room3.jpg",
    content: "무암동인근 2인용 원룸입니다. 전세 전환가능",
    price: 550000
    },
    {
    id : 4,
    title: "MyeongIl Apartment flat",
    image: "https://codingapple1.github.io/vue/room4.jpg",
    content: "탄천동 아파트 월세, 남향, 역 5분거리, 허위매물아님",
    price: 680000
    },
    {
    id : 5,
    title: "Banziha One Room",
    image: "https://codingapple1.github.io/vue/room5.jpg",
    content: "반지하 원룸입니다. 비올 때 물가끔 새는거 빼면 좋아요",
    price: 370000
  }];

 

 

array를 기준으로 먼저 나온 문자의 title이 크면 양수, 작으면 음수를 리턴한다. 즉) a가 b보다 작으면 순서를 바꾸게 되는 것. 이렇게 여러줄 입력하지 않는 방법은 ?? 

 

    titleSort(){
      this.원룸들.sort(function(a,b){
        if(a.title>b.title) {
          return 1
        }else if(a.title<b.title){
          return -1
        }else{
          return 0
        }
      })
    }

 

 

바로 아래 한 줄을 입력하는 것.! 

    titleSort(){
      this.원룸들.sort(function(a,b){
         return a.title.localeCompare(b.title)
        
    }
반응형