Dev./javascript

[JS] 객체 배열을 문자열 기준으로 정렬하기

인쥭 2022. 9. 19. 15:04
반응형

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' }
]