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

매출 상위 N명만 보기Show only the top N by sales

'상위 N행' 전용 연산자는 없지만, N번째 값을 구해서 '그 값 이상'으로 걸면 같은 효과를 내요. 정렬을 함께 걸어 순위대로 보여 줘요.There is no top-N operator; find the Nth value and filter for at least that value. Sort alongside to show the ranking.

활용Intermediate
직접 써 보기Live preview매출 상위 N명만 보기Show only the top N by sales

코드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="top">
      <option value="all" selected>전체</option>
      <option value="3">상위 3명</option>
      <option value="5">상위 5명</option>
      <option value="10">상위 10명</option>
    </select>
  </div>
  <div id="grid" style="height: 700px"></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('top').addEventListener('change', (event) => actions.top(api, event.target.value));
example.js
const reps = [
  '김민준',
  '이서연',
  '박지호',
  '최유나',
  '정도윤',
  '한소희',
  '오세훈',
  '김서윤',
  '장하은',
  '윤재민',
];
const regions = ['서울', '부산', '대구', '광주'];
// 매출은 모두 다른 값이라 '상위 N명'이 정확히 N행이에요.
export const options = {
  columns: [
    { id: 'rep', title: '담당자', width: 120 },
    { id: 'region', title: '지역', width: 90 },
    {
      id: 'sales',
      title: '매출(만원)',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('ko-KR'),
    },
  ],
  rows: Array.from({ length: 20 }, (_, i) => ({
    id: i + 1,
    rep: reps[i % 10],
    region: regions[(i * 3) % 4],
    sales: 1200 + ((i * 7919) % 6400) + i,
  })),
  rowKey: 'id',
};
// 상위 N행 필터는 따로 연산자가 없어요. 전체 값을 큰 순으로 놓고 N번째 값을 구한 뒤,
// 그 값 '이상'(gte)만 보이게 하면 돼요. 값이 같은 행이 있으면 N행보다 많아질 수 있어요.
function topN(api, n) {
  const values = options.rows.map((row) => row.sales).sort((a, b) => b - a);
  const cutoff = values[Math.min(n, values.length) - 1];
  api.setFilterModel({
    match: 'all',
    items: [{ columnId: 'sales', operator: 'gte', value: cutoff }],
  });
  api.setSortModel([{ columnId: 'sales', direction: 'desc' }]);
}
export function setup(api, log) {
  const off = api.on('filterChanged', () => log({
    ko: `보이는 행 ${api.getVisibleRowCount()} / 전체 ${api.getRowCount()}`,
    en: `Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`,
  }));
  return () => off();
}
export const actions = {
  top: (api, value) => {
    if (!value || value === 'all') {
      api.setFilterModel(null);
      api.setSortModel([]);
      return;
    }
    topN(api, Number(value));
  },
};

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="View" id="top">
      <option value="all" selected>All</option>
      <option value="3">Top 3</option>
      <option value="5">Top 5</option>
      <option value="10">Top 10</option>
    </select>
  </div>
  <div id="grid" style="height: 700px"></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('top').addEventListener('change', (event) => actions.top(api, event.target.value));
example.js
const reps = [
  'Liam Carter',
  'Emma Stone',
  'Noah Kim',
  'Olivia Park',
  'Ethan Brooks',
  'Sophia Lee',
  'Mason Reed',
  'Ava Morgan',
  'Lucas Hayes',
  'Mia Foster',
];
const regions = ['New York', 'Boston', 'Austin', 'Seattle'];
// Sales are all distinct, so "top N" is exactly N rows.
export const options = {
  columns: [
    { id: 'rep', title: 'Rep', width: 140 },
    { id: 'region', title: 'Region', width: 110 },
    {
      id: 'sales',
      title: 'Sales ($)',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
    },
  ],
  rows: Array.from({ length: 20 }, (_, i) => ({
    id: i + 1,
    rep: reps[i % 10],
    region: regions[(i * 3) % 4],
    sales: 12000 + ((i * 79190) % 64000) + i * 10,
  })),
  rowKey: 'id',
};
// There is no separate operator for a top-N filter. Sort all values from largest, take the N-th value,
// and show only rows at least that value (gte). Ties can make the result larger than N rows.
function topN(api, n) {
  const values = options.rows.map((row) => row.sales).sort((a, b) => b - a);
  const cutoff = values[Math.min(n, values.length) - 1];
  api.setFilterModel({
    match: 'all',
    items: [{ columnId: 'sales', operator: 'gte', value: cutoff }],
  });
  api.setSortModel([{ columnId: 'sales', direction: 'desc' }]);
}
export function setup(api, log) {
  const off = api.on('filterChanged', () => log(`Visible rows ${api.getVisibleRowCount()} / total ${api.getRowCount()}`));
  return () => off();
}
export const actions = {
  top: (api, value) => {
    if (!value || value === 'all') {
      api.setFilterModel(null);
      api.setSortModel([]);
      return;
    }
    topN(api, Number(value));
  },
};