# Pick random lines from a text document

Split text into lines and return count of them in random order.

Canonical: https://1loc.dev/random/pick-random-lines-from-a-text-document/
Version: 1.0.0
Runtime: JavaScript · Node.js 22 / modern browsers
Verification: Usage lines executed in Node.js 22 and headless Chromium; no external services
Updated: 2026-10-28

## Implementation

```javascript
function randomLines(text, count) {
  const lines = text.split(/\r?\n/);
  for (let i = lines.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [lines[i], lines[j]] = [lines[j], lines[i]];
  }
  return lines.slice(0, count);
}
```

## Usage

```javascript
const poem = `one
two
three
four
five`;
randomLines(poem, 4).length; // → 4
new Set(randomLines(poem, 5)).size; // → 5
```

Lines marked → were executed in Node.js 22 and in headless Chromium, and each result was compared with the value shown. Lines marked e.g. are illustrative.

## Limits

- The original had the same reduce-and-splice flaw as Get random items of an array: requesting more than half the lines returned fewer.
- Lines split on LF and CRLF. A trailing newline adds one empty line, which can be drawn.

The function does not validate its arguments. Add checks where it receives untrusted input.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/pick-random-lines-from-a-text-document.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: See original repository history
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: Shuffles the lines and slices; the original returned fewer lines than requested when asked for more than half. Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
