Dev Helpers
← Back

Find rows with an adjacent free pair

Find rows with an adjacent free pair. Build the result in an App Router server page and send the rendered entries to the client.

Open this example in the interactive library

Source code

// app/find-rows-with-an-adjacent-free-pair/page.tsx
export const metadata = { title: "Find rows with an adjacent free pair" };
export default function Page() {
  const rows = [
    { row: "A", seat: 1, held: true },
    { row: "A", seat: 2, held: false },
    { row: "B", seat: 1, held: false },
    { row: "B", seat: 2, held: false },
  ];
  const result = rows
    .filter(
      (r) =>
        !r.held &&
        rows.some((x) => x.row === r.row && !x.held && x.seat === r.seat + 1),
    )
    .map((r) => ({ row: r.row, pair: [r.seat, r.seat + 1] }));
  const entries = Object.entries(
    typeof result === "object" && result !== null ? result : { value: result },
  );
  return (
    <section>
      <h2>{"Find rows with an adjacent free pair"}</h2>
      {entries.length ? (
        <dl>
          {entries.map(([key, value]) => (
            <div key={key}>
              <dt>{key}</dt>
              <dd>
                {typeof value === "string" ? value : JSON.stringify(value)}
              </dd>
            </div>
          ))}
        </dl>
      ) : (
        <p>No matching entries.</p>
      )}
    </section>
  );
}