티스토리 뷰

반응형

String.prototype.localeCompare()를 배열의 sort()와 함께 사용하여 다음과 같이 코드를 작성할 수 있다.

 

String.prototype.localeCompare() - JavaScript | MDN

The localeCompare() method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order.

developer.mozilla.org

const arr = [
  { name: 'folder_1' },
  { name: 'folder_2' },
  { name: 'folder_3' },
  { name: 'folder_1_1' },
  { name: 'folder_1_2' },
  { name: 'folder_2_1' },
  { name: 'folder_3_1' },
  { name: 'folder_3_3' },
  { name: 'folder_1_1_1' },
  { name: 'folder_1_1_2' },
  { name: 'folder_1_1_3' },
  { name: 'folder_1_1_4' },
];

console.log(
    arr.sort((a, b) => a.name.localeCompare(b.name))
);

실행 결과는 다음과 같다.

[
  { name: 'folder_1' },
  { name: 'folder_1_1' },
  { name: 'folder_1_1_1' },
  { name: 'folder_1_1_2' },
  { name: 'folder_1_1_3' },
  { name: 'folder_1_1_4' },
  { name: 'folder_1_2' },
  { name: 'folder_2' },
  { name: 'folder_2_1' },
  { name: 'folder_3' },
  { name: 'folder_3_1' },
  { name: 'folder_3_3' }
]

 

댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함