Develope/Javascript

[Javascript]sort()를 사용하여 배열(Array)의 아이템 정렬하기

oper0116 2020. 6. 15. 13:32
반응형

개요

배열(Array)에 있는 아이템을 오름차순, 내림차순으로 정렬해야 하는 경우가 발생합니다. 이러한 경우 sort() 메서드를 사용하여 배열의 아이템을 정렬을 할 수 있습니다.
sort() 메소드는 배열의 요소를 정렬하여 정렬된 배열을 반환합니다.

arr.sort([compareFunction])

compareFunction

compareFunction가 존재하지 않을 경우 문자열의 아스키코드(AsciiCode) 변환된 값의 오름차순으로 정렬된 배열을 반환합니다.

const arry1 = [ 3, 1, 2 ];
arry1.sort();    // [1, 2, 3]

const arry2 = [ 'b', 'a', 'c' ];
arry2.sort(); // ["a", "b", "c"]

const arry3 = [ 2, 1, 'b', 'a', 'c', 80 ];
arry3.sort();   // [1, 2, "a", "b", "c"]

아스키코드로 변환된 값으로 정렬하기 때문에 숫자의 크기대로 정렬되지 않습니다.

const arr = [1, 11, 4, 2, 222, 3, 10];
arr.sort(); // [1, 10, 11, 2, 222, 3, 4]

크기대로 정렬하고자 할 경우 compareFunction를 정의하여 다음과 같이 사용합니다.

const arr = [1, 11, 4, 2, 222, 3, 10];

// 오름차순
arr.sort((a, b) => { 
    return a - b; // [1, 2, 3, 4, 10, 11, 222]
});

 // 내림차순
arr.sort((a, b) => {
    return b - a; // [222, 11, 10, 4, 3, 2, 1]
});

객체의 속성값을 비교할 수 있습니다.

const students = [
    { key: 1, name: 'a1', age: 13 },
    { key: 2, name: 'b1', age: 20 },
    { key: 3, name: 'c1', age: 25 },
    { key: 4, name: 'd1', age: 23 },
    { key: 5, name: 'e1', age: 32 }
];

// 오름차순
students.sort((a, b) => {
  if (a.age > b.age) {
    return 1;
  }
  if (a.age < b.age) {
    return -1;
  }
  return 0;
});

// [
//    {key: 1, name: "a1", age: 13},
//    {key: 2, name: "b1", age: 20},
//    {key: 4, name: "d1", age: 23},
//    {key: 3, name: "c1", age: 25},
//    {key: 5, name: "e1", age: 32}
// ]


// 내림차순
students.sort((a, b) => {
  if (a.age < b.age) {
    return 1;
  }
  if (a.age > b.age) {
    return -1;
  }
  return 0;
});

// [
//   {key: 5, name: "e1", age: 32},
//   {key: 3, name: "c1", age: 25},
//   {key: 4, name: "d1", age: 23},
//   {key: 2, name: "b1", age: 20},
//   {key: 1, name: "a1", age: 13}
// ]


undefined가 있는 경우

정렬하고자 하는 배열에 undefined가 있는 경우에는 undefined가 마지막으로 정렬되어 반환됩니다.

const arry = [ 1, 5, 3, undefined, 16];
arry.sort();    // [1, 16, 3, 5, undefined]

null이 있는 경우

null이 있는 경우 null'null' 문자열로 형변환되어 정렬됩니다.

const arry = ['a', 'c', 'b', null, 'z'] 
arry.sort();    // ["a", "b", "c", null, "z"]

참고자료

(MDN Web Docs: sort)[https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/sort]

반응형