(underscore.js) _.sortBy()

호두파파·2021년 2월 26일
0

underScore.js

목록 보기
7/9

sortBy()

collection 값들을 원하는 필드를 기준으로 정렬해준다 특히 윕페이지에서 데이터를 모두 불러오는 경우 sortBy()를 사용하면 매우 편리하게 정렬할 수 있다. 프론트엔드 프레임워크를 사용하는 싱글 페이지 어플리케이션에서 데이터를 조작할때 유용하게 사용할 수 있다.

_.sortBy(collection, fieldName);

컬렉션 값에 소팅을 원하는 필드명을 입력한다.

예제

var items = [
  { no: 1, name: 'web', date: '180804' },
  { no: 2, name: 'is', date: '180802' },
  { no: 3, name: 'free', date: '180801' },
  { no: 4, name: 'forever', date: '180804' },
];

위와 같은 collection 데이터가 존재하는 경우 각각의 필드명에 대해 정렬할 수 있다.

_.sortBy(items, 'date');

// 출력결과
[
  {no: 3, name: "free", date: "180801"},
  {no: 2, name: "is", date: "180802"},
  {no: 1, name: "web", date: "180804"},
  {no: 4, name: "forever", date: "180804"}
]

date를 기준으로 정렬시켜보았다.

오름차순, 내림차순으로 변경하기

reverse내장함수를 사용하면 정렬이 쉽게 가능하다. 이 메소드는 자바스크립트의 배열 메소드로 배열의 순서를 역순으로 바꾸어 줄 수 있다. 오름차순인 데이터에 reverse()를 사용하면 반대로 가져오므로 내림차순과 동일한 효과를 가져올 수 있다.

_.sortBy(items, 'date').reverse();

// 출력결과
[
  {no: 4, name: "forever", date: "180804"},
  {no: 1, name: "web", date: "180804"},
  {no: 2, name: "is", date: "180802"},
  {no: 3, name: "free", date: "180801"}
]

sortBy() 복수개의 컬럼으로 정렬하기

하나가 아닌 여러개의 컬럼을 기준으로 정렬할 수 있다.
예를 들어 name 그리고 date를 기준으로 정렬하는 것이 가능하다.

_.sortBy(items, ['date', 'name']);

위 코드를 수행하면 date, name으로 각각 정렬되어 결가가 나타난다.

[
  {no: 3, name: "free", date: "180801"},
  {no: 2, name: "is", date: "180802"},
  {no: 4, name: "forever", date: "180804"},
  {no: 1, name: "web", date: "180804"}
]

구현하기

_.sortBy = function(collection, iterator) {
    if(typeof iterator === 'string') {
      collection.sort(function(a, b) {
        return a[iterator] - b[iterator];
      })
    } else {
      collection.sort(function(a, b) {
        return iterator(a) - iterator(b);
      });
    }
    return collection;
  };
profile
안녕하세요 주니어 프론트엔드 개발자 양윤성입니다.

0개의 댓글