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

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

grouping.sortByTotal에 컬럼을 적으면 같은 부모 안의 그룹이 그 컬럼의 그룹 합계 순서로 놓여요. 도우미 컬럼이 필요 없어요.Set grouping.sortByTotal to a column and sibling groups are ordered by that column's group total. No helper column needed.

활용Intermediate
직접 써 보기Live preview그룹을 합계 순으로 바로 정렬하기Sort groups by their total directly

코드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="order">
      <option value="desc" selected>합계 큰 순</option>
      <option value="asc">합계 작은 순</option>
      <option value="none">정렬 안 함</option>
    </select>
  </div>
  <div id="grid" style="height: 360px"></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('order').addEventListener('change', (event) => actions.order(api, event.target.value));
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 grouping = (order) => ({
  by: ['team'],
  expandDepth: 0,
  // 같은 부모 안의 그룹을 sales 합계 순으로 놓아요. 없으면 줄이 처음 나타난 순서예요.
  ...(order === 'none' ? {} : { sortByTotal: { column: 'sales', direction: order } }),
});
export const options = {
  columns: [
    { id: 'team', title: '팀', width: 100 },
    { id: 'member', title: '담당자', width: 90 },
    {
      id: 'sales',
      title: '매출(만원)',
      kind: 'number',
      width: 110,
      align: 'end',
      aggregate: 'sum',
    },
  ],
  rows,
  rowKey: 'id',
  grouping: grouping('desc'),
};
let say = () => { };
// 사용자가 '그룹 정렬' 선택으로 고른 값. 머리글 정렬을 풀면 이 값으로 돌아가요.
let chosen = 'desc';
const WORDS_EN = {
  desc: 'Sorted by total, largest first',
  asc: 'Sorted by total, smallest first',
  none: 'Not sorted. Rows are in the order they first appeared',
};
const WORDS = {
  desc: '합계 큰 순으로 정렬했어요',
  asc: '합계 작은 순으로 정렬했어요',
  none: '정렬하지 않아요. 줄이 처음 나타난 순서예요',
};
function showChoice(order) {
  const select = document.getElementById('order');
  if (select instanceof HTMLSelectElement && select.value !== order)
    select.value = order;
}
export function setup(api, log) {
  say = log;
  log({ ko: WORDS.desc, en: WORDS_EN.desc });
  // 매출 머리글을 눌러 정렬하면 그룹 순서의 방향이 그 방향을 따라가요. 선택 칸도 실제 순서에 맞춰 바꿔요.
  const off = api.on('sortChanged', ({ sortModel }) => {
    const item = sortModel.find((s) => s.columnId === 'sales');
    if (chosen === 'none' || !item)
      return showChoice(chosen);
    showChoice(item.direction);
    log({
      ko: `매출 머리글 정렬을 따라 ${item.direction === 'asc' ? '합계 작은 순' : '합계 큰 순'}이 됐어요`,
      en: `Following the sales header sort: ${item.direction === 'asc' ? 'smallest total first' : 'largest total first'}`,
    });
  });
  return () => off();
}
export const actions = {
  order: (api, value) => {
    chosen = (value ?? 'desc');
    api.setOptions({ grouping: grouping(chosen) });
    say({ ko: WORDS[chosen], en: WORDS_EN[chosen] });
  },
};

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="Group order" id="order">
      <option value="desc" selected>Largest first</option>
      <option value="asc">Smallest first</option>
      <option value="none">Off</option>
    </select>
  </div>
  <div id="grid" style="height: 360px"></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('order').addEventListener('change', (event) => actions.order(api, event.target.value));
example.js
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const members = ['Liam Carter', 'Emma Stone', 'Noah Kim', 'Olivia Park', 'Mia Johnson'];
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,
}));
const grouping = (order) => ({
  by: ['team'],
  expandDepth: 0,
  // Place the groups inside the same parent in order of their sales total. Without it, rows keep the order they first appeared.
  ...(order === 'none' ? {} : { sortByTotal: { column: 'sales', direction: order } }),
});
export const options = {
  columns: [
    { id: 'team', title: 'Team', width: 100 },
    { id: 'member', title: 'Owner', width: 120 },
    {
      id: 'sales',
      title: 'Sales ($)',
      kind: 'number',
      width: 110,
      align: 'end',
      aggregate: 'sum',
    },
  ],
  rows,
  rowKey: 'id',
  grouping: grouping('desc'),
};
let say = () => { };
// The value the user picked in the "group order" select. Clearing the header sort returns to this value.
let chosen = 'desc';
const WORDS = {
  desc: 'Sorted by total, largest first',
  asc: 'Sorted by total, smallest first',
  none: 'Not sorted. Rows are in the order they first appeared',
};
function showChoice(order) {
  const select = document.getElementById('order');
  if (select instanceof HTMLSelectElement && select.value !== order)
    select.value = order;
}
export function setup(api, log) {
  say = log;
  log(WORDS.desc);
  // Sorting by the Sales header makes the group order follow that direction. The select is updated to match the real order.
  const off = api.on('sortChanged', ({ sortModel }) => {
    const item = sortModel.find((s) => s.columnId === 'sales');
    if (chosen === 'none' || !item)
      return showChoice(chosen);
    showChoice(item.direction);
    log(`Following the sales header sort: ${item.direction === 'asc' ? 'smallest total first' : 'largest total first'}`);
  });
  return () => off();
}
export const actions = {
  order: (api, value) => {
    chosen = (value ?? 'desc');
    api.setOptions({ grouping: grouping(chosen) });
    say(WORDS[chosen]);
  },
};