본문으로 건너뛰기Skip to content
예제 첫화면Examples home

그룹을 합계 순으로 정렬하기Sort groups by their total

합계가 큰 팀을 위로 올리고, 이름순으로 바꾸고, 그룹 안의 순서만 바꿔 봐요.Move the team with the largest total to the top, sort by name, or reorder only inside the groups.

심화Advanced
직접 써 보기Live preview그룹을 합계 순으로 정렬하기Sort groups by their total

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="정렬" id="sort">
      <option value="none" selected>정렬 없음</option>
      <option value="biggest">팀 합계 큰 순</option>
      <option value="smallest">팀 합계 작은 순</option>
      <option value="name">팀 이름 순</option>
      <option value="inner">팀 이름 순, 그룹 안은 매출 큰 순</option>
    </select>
    <button type="button" id="expandAll">모두 펼치기</button>
    <button type="button" id="collapseAll">모두 접기</button>
  </div>
  <div id="grid" style="height: 330px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('sort').addEventListener('change', (event) => actions.sort(api, event.target.value));
document.getElementById('expandAll').addEventListener('click', () => actions.expandAll(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(api));
example.js
const teams = ['알파팀', '베타팀', '감마팀', '델타팀'];
const members = ['김서연', '이준호', '박민지', '최도윤', '정하은'];
const rows = Array.from({ length: 20 }, (_, i) => ({
  id: i + 1,
  team: teams[i % 4],
  member: members[Math.floor(i / 4)],
  sales: 100 + ((i * 53) % 170),
}));
// 정렬은 먼저 줄을 정렬한 다음 그룹으로 모아요. 그래서 매출로 정렬하면 각 그룹 안의 순서가 바뀌어요.
// 그룹 줄은 줄 순서에 따라 나타나기 때문에, 합계가 큰 그룹을 위로 올리려면 "팀 합계" 도우미 컬럼을 두고
// 그 컬럼으로 먼저 정렬해요.
const totals = new Map();
for (const row of rows)
  totals.set(row.team, (totals.get(row.team) ?? 0) + row.sales);
export const options = {
  columns: [
    { id: 'team', title: '팀', width: 110 },
    { id: 'member', title: '담당자', width: 110 },
    {
      id: 'sales',
      title: '매출(만원)',
      kind: 'number',
      width: 110,
      align: 'end',
      aggregate: 'sum',
    },
    {
      id: 'teamTotal',
      title: '팀 합계',
      kind: 'number',
      width: 100,
      align: 'end',
      getValue: (row) => totals.get(row.team) ?? 0,
    },
  ],
  rows,
  rowKey: 'id',
  grouping: { by: ['team'], expandDepth: 0 },
};
const titles = {
  team: '팀',
  member: '담당자',
  sales: '매출',
  teamTotal: '팀 합계',
};
const models = {
  biggest: [
    { columnId: 'teamTotal', direction: 'desc' },
    { columnId: 'sales', direction: 'desc' },
  ],
  smallest: [
    { columnId: 'teamTotal', direction: 'asc' },
    { columnId: 'sales', direction: 'desc' },
  ],
  name: [{ columnId: 'team', direction: 'asc' }],
  inner: [
    { columnId: 'team', direction: 'asc' },
    { columnId: 'sales', direction: 'desc' },
  ],
  none: [],
};
export function setup(api, log) {
  return api.on('sortChanged', ({ sortModel }) => log({
    ko: sortModel
      .map((item) => `${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? '오름차순' : '내림차순'}`)
      .join(', ') || '정렬을 풀었어요.',
    en: sortModel
      .map((item) => `${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? 'ascending' : 'descending'}`)
      .join(', ') || 'Sort cleared.',
  }));
}
export const actions = {
  sort: (api, value) => api.setSortModel(models[value ?? 'none'] ?? []),
  expandAll: (api) => api.expandAll(),
  collapseAll: (api) => api.collapseAll(),
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="Sort" id="sort">
      <option value="none" selected>No sort</option>
      <option value="biggest">Team total, largest first</option>
      <option value="smallest">Team total, smallest first</option>
      <option value="name">Team name</option>
      <option value="inner">Team name; sales desc inside groups</option>
    </select>
    <button type="button" id="expandAll">Expand all</button>
    <button type="button" id="collapseAll">Collapse all</button>
  </div>
  <div id="grid" style="height: 330px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('sort').addEventListener('change', (event) => actions.sort(api, event.target.value));
document.getElementById('expandAll').addEventListener('click', () => actions.expandAll(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(api));
example.js
const teams = ['Alpha', 'Beta', 'Gamma', 'Delta'];
const members = ['Emma Stone', 'Liam Carter', 'Mia Johnson', 'Ethan Brown', 'Zoe Miller'];
const rows = Array.from({ length: 20 }, (_, i) => ({
  id: i + 1,
  team: teams[i % 4],
  member: members[Math.floor(i / 4)],
  sales: 1000 + ((i * 53) % 170) * 10,
}));
// Sorting orders the rows first and then collects them into groups. So sorting by sales changes the order inside each group.
// Group rows appear according to row order, so to move the groups with the biggest totals to the top,
// add a "Team total" helper column and sort by it first.
const totals = new Map();
for (const row of rows)
  totals.set(row.team, (totals.get(row.team) ?? 0) + row.sales);
export const options = {
  columns: [
    { id: 'team', title: 'Team', width: 110 },
    { id: 'member', title: 'Owner', width: 120 },
    {
      id: 'sales',
      title: 'Sales ($)',
      kind: 'number',
      width: 110,
      align: 'end',
      aggregate: 'sum',
    },
    {
      id: 'teamTotal',
      title: 'Team total',
      kind: 'number',
      width: 130,
      align: 'end',
      getValue: (row) => totals.get(row.team) ?? 0,
    },
  ],
  rows,
  rowKey: 'id',
  grouping: { by: ['team'], expandDepth: 0 },
};
const titles = {
  team: 'Team',
  member: 'Owner',
  sales: 'Sales',
  teamTotal: 'Team total',
};
const models = {
  biggest: [
    { columnId: 'teamTotal', direction: 'desc' },
    { columnId: 'sales', direction: 'desc' },
  ],
  smallest: [
    { columnId: 'teamTotal', direction: 'asc' },
    { columnId: 'sales', direction: 'desc' },
  ],
  name: [{ columnId: 'team', direction: 'asc' }],
  inner: [
    { columnId: 'team', direction: 'asc' },
    { columnId: 'sales', direction: 'desc' },
  ],
  none: [],
};
export function setup(api, log) {
  return api.on('sortChanged', ({ sortModel }) => log(sortModel
    .map((item) => `${titles[item.columnId] ?? item.columnId} ${item.direction === 'asc' ? 'ascending' : 'descending'}`)
    .join(', ') || 'Sort cleared.'));
}
export const actions = {
  sort: (api, value) => api.setSortModel(models[value ?? 'none'] ?? []),
  expandAll: (api) => api.expandAll(),
  collapseAll: (api) => api.collapseAll(),
};