collect.js를 활용한 데이터 정렬과 페이지네이션 구현 가이드

collect.js 시작하기

collect.js는 배열과 객체를 다루기 위한 가벼운 JavaScript 라이브러리입니다. npm을 통해 쉽게 설치할 수 있습니다.

npm install collect.js --save

설치 후 프로젝트에서 다음과 같이 사용합니다.

const collect = require('collect.js');
const items = collect([{ id: 2, name: 'Banana' }, { id: 1, name: 'Apple' }]);

데이터 정렬 방법

기본 정렬: sort()와 sortDesc()

// 오름차순 정렬
const ascending = collect([3, 1, 2]).sort(); // [1, 2, 3]

// 내림차순 정렬
const descending = collect([3, 1, 2]).sortDesc(); // [3, 2, 1]

객체 배열 정렬: sortBy()와 sortByDesc()

const fruits = collect([
  { name: 'Banana', price: 2.5 },
  { name: 'Apple', price: 1.8 },
  { name: 'Orange', price: 3.2 }
]);

// 가격 오름차순 정렬
const byPrice = fruits.sortBy('price'); // Apple(1.8), Banana(2.5), Orange(3.2)

// 이름 내림차순 정렬
const byNameDesc = fruits.sortByDesc('name');

사용자 정의 정렬

// 문자열 길이 기준 정렬
const words = collect(['apple', 'banana', 'cherry']);
const byLength = words.sort((a, b) => a.length - b.length);

페이지네이션 구현

forPage() 메서드 사용

const numbers = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);

// 2페이지, 페이지당 3개 항목
const page2 = numbers.forPage(2, 3); // [4, 5, 6]

skip()과 take() 조합

// 처음 3개 건너뛰고 다음 3개 가져오기 (2페이지, 페이지당 3개)
const customPage = numbers.skip(3).take(3); // [4, 5, 6]

정렬과 페이지네이션 결합

const products = collect([
  { id: 3, name: 'Laptop', price: 999 },
  { id: 1, name: 'Mouse', price: 25 },
  { id: 2, name: 'Keyboard', price: 50 }
]);

// 가격 정렬 후 1페이지 데이터 가져오기 (페이지당 2개)
const sortedAndPaged = products.sortBy('price').forPage(1, 2);
// 결과: Mouse(25), Keyboard(50)

대용량 데이터 처리

// 10만 개 데이터 처리 예시
const largeData = collect(Array.from({length: 100000}, (_, i) => ({ id: i, value: Math.random() })));
const result = largeData.sortBy('value').forPage(5, 20);

중첩 객체 정렬

const users = collect([
  { user: { name: 'John', age: 30 } },
  { user: { name: 'Jane', age: 25 } }
]);

const sortedByAge = users.sortBy('user.age');

collect.js의 sortBy(), forPage() 메서드를 활용하면 데이터 정렬과 페이지네이션을 간결하게 구현할 수 있습니다. 자세한 내용은 공식 문서를 참조하세요.

태그: collect.js JavaScript 데이터정렬 페이지네이션 배열처리

6월 30일 18:02에 게시됨