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

내가 만든 식으로 합계 줄 계산하기Calculate the total row with your own formula

최대와 최소의 차이, 중앙값, 상위 3곳의 합, 목표 대비 달성률처럼 기본 계산에 없는 값도 직접 만든 계산식 하나로 합계 줄에 넣을 수 있어요. 필터를 걸면 보이는 줄만으로 다시 계산해요.Values the built-in calculations do not cover, such as the max-min gap, the median, the sum of the top three or the share of a target, fit in one formula of your own. With a filter the row recalculates from the visible rows only.

활용Intermediate
직접 써 보기Live preview내가 만든 식으로 합계 줄 계산하기Calculate the total row with your own formula

코드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="region">
      <option value="all" selected>전체</option>
      <option value="수도권">수도권</option>
      <option value="영남">영남</option>
      <option value="호남">호남</option>
      <option value="충청">충청</option>
      <option value="제주">제주</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 } from './example';
const api = createGrid(document.getElementById('grid'), options);
document.getElementById('region').addEventListener('change', (event) => actions.region(api, event.target.value));
example.js
const branches = [
  '서울 본점',
  '강남점',
  '부산점',
  '대구점',
  '인천점',
  '광주점',
  '대전점',
  '제주점',
];
const regions = ['수도권', '수도권', '영남', '영남', '수도권', '호남', '충청', '제주'];
// 단위는 백만원이에요. 지점마다 1~6월 매출이 있어요.
const sales = (i, k) => 20 + ((i * 13 + k * 7) % 70);
const rows = branches.map((branch, i) => ({
  id: i + 1,
  branch,
  region: regions[i],
  m1: sales(i, 1),
  m2: sales(i, 2),
  m3: sales(i, 3),
  m4: sales(i, 4),
  m5: sales(i, 5),
  m6: sales(i, 6),
}));
const money = (value) => Number(value).toLocaleString('ko-KR');
// 기본 계산(합계·평균…)으로 안 되는 값은 aggregate에 함수를 넣어요. 함수는 그 컬럼의 값들을 받아서 계산 결과를 돌려줘요.
// 필터를 걸면 보이는 줄의 값만 들어와서, 합계 줄도 "지금 보이는 줄 기준"으로 다시 계산돼요.
const numbers = (values) => values.filter((v) => typeof v === 'number');
const range = (values) => {
  const list = numbers(values);
  return list.length ? Math.max(...list) - Math.min(...list) : null;
};
const median = (values) => {
  const list = numbers(values).sort((a, b) => a - b);
  if (!list.length)
    return null;
  const mid = Math.floor(list.length / 2);
  return list.length % 2 ? list[mid] : (list[mid - 1] + list[mid]) / 2;
};
const topThree = (values) => numbers(values)
  .sort((a, b) => b - a)
  .slice(0, 3)
  .reduce((sum, v) => sum + v, 0);
const TARGET = 400; // 6월 목표(백만원)
const attainment = (values) => numbers(values).reduce((sum, v) => sum + v, 0) / TARGET;
const shown = (make) => (value) => value == null ? '-' : make(Number(value));
export const options = {
  columns: [
    { id: 'branch', title: '지점', width: 120 },
    { id: 'region', title: '권역', width: 90 },
    {
      id: 'm3',
      title: '3월 (최대-최소)',
      kind: 'number',
      width: 140,
      align: 'end',
      formatValue: money,
      aggregate: range,
      aggregateFormat: shown((v) => `차이 ${v}`),
    },
    {
      id: 'm4',
      title: '4월 (중앙값)',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: money,
      aggregate: median,
      aggregateFormat: shown((v) => `중앙 ${v}`),
    },
    {
      id: 'm5',
      title: '5월 (상위 3곳)',
      kind: 'number',
      width: 140,
      align: 'end',
      formatValue: money,
      aggregate: topThree,
      aggregateFormat: shown((v) => `상위3 ${v}`),
    },
    {
      id: 'm6',
      title: '6월 (목표 달성)',
      kind: 'number',
      width: 140,
      align: 'end',
      formatValue: money,
      aggregate: attainment,
      aggregateFormat: shown((v) => `${Math.round(v * 100)}%`),
    },
  ],
  rows,
  rowKey: 'id',
  summary: { label: '직접 계산' },
};
export const actions = {
  region: (api, value) => api.setFilterModel(value && value !== 'all'
    ? { match: 'all', items: [{ columnId: 'region', operator: 'equals', value }] }
    : null),
};

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="Region" id="region">
      <option value="all" selected>All</option>
      <option value="수도권">Capital area</option>
      <option value="영남">Yeongnam</option>
      <option value="호남">Honam</option>
      <option value="충청">Chungcheong</option>
      <option value="제주">Jeju</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 } from './example';
const api = createGrid(document.getElementById('grid'), options);
document.getElementById('region').addEventListener('change', (event) => actions.region(api, event.target.value));
example.js
const branches = ['Seoul HQ', 'Gangnam', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon', 'Jeju'];
const regions = [
  'Capital',
  'Capital',
  'Yeongnam',
  'Yeongnam',
  'Capital',
  'Honam',
  'Chungcheong',
  'Jeju',
];
// Units are $ thousands. Each branch has sales for January to June.
const sales = (i, k) => 20 + ((i * 13 + k * 7) % 70);
const rows = branches.map((branch, i) => ({
  id: i + 1,
  branch,
  region: regions[i],
  m1: sales(i, 1),
  m2: sales(i, 2),
  m3: sales(i, 3),
  m4: sales(i, 4),
  m5: sales(i, 5),
  m6: sales(i, 6),
}));
const money = (value) => Number(value).toLocaleString('en-US');
// For values the built-in calculations (total, average...) cannot produce, pass a function to aggregate. It receives the column's values and returns the result.
// With a filter applied only the visible rows' values come in, so the summary row is recalculated "based on the rows shown now".
const numbers = (values) => values.filter((v) => typeof v === 'number');
const range = (values) => {
  const list = numbers(values);
  return list.length ? Math.max(...list) - Math.min(...list) : null;
};
const median = (values) => {
  const list = numbers(values).sort((a, b) => a - b);
  if (!list.length)
    return null;
  const mid = Math.floor(list.length / 2);
  return list.length % 2 ? list[mid] : (list[mid - 1] + list[mid]) / 2;
};
const topThree = (values) => numbers(values)
  .sort((a, b) => b - a)
  .slice(0, 3)
  .reduce((sum, v) => sum + v, 0);
const TARGET = 400; // June target ($ thousands)
const attainment = (values) => numbers(values).reduce((sum, v) => sum + v, 0) / TARGET;
const shown = (make) => (value) => value == null ? '-' : make(Number(value));
export const options = {
  columns: [
    { id: 'branch', title: 'Branch', width: 120 },
    { id: 'region', title: 'Region', width: 90 },
    {
      id: 'm3',
      title: 'Mar (max - min)',
      kind: 'number',
      width: 140,
      align: 'end',
      formatValue: money,
      aggregate: range,
      aggregateFormat: shown((v) => `Diff ${v}`),
    },
    {
      id: 'm4',
      title: 'Apr (median)',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: money,
      aggregate: median,
      aggregateFormat: shown((v) => `Median ${v}`),
    },
    {
      id: 'm5',
      title: 'May (top 3)',
      kind: 'number',
      width: 140,
      align: 'end',
      formatValue: money,
      aggregate: topThree,
      aggregateFormat: shown((v) => `Top3 ${v}`),
    },
    {
      id: 'm6',
      title: 'Jun (target met)',
      kind: 'number',
      width: 140,
      align: 'end',
      formatValue: money,
      aggregate: attainment,
      aggregateFormat: shown((v) => `${Math.round(v * 100)}%`),
    },
  ],
  rows,
  rowKey: 'id',
  summary: { label: 'Custom calc' },
};
export const actions = {
  region: (api, value) => api.setFilterModel(value && value !== 'all'
    ? { match: 'all', items: [{ columnId: 'region', operator: 'equals', value }] }
    : null),
};