Pick random lines from a text document

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

JavaScriptNode.js & browsers Version 1.0.0 · MIT · .md

pick-random-lines-from-a-text-document.js
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

usage.js
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.

Know the 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 above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.

Source & maintenance

Based on Pick random lines from a text document from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

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.

Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.

Usage lines executed in Node.js 22 and headless Chromium; no external services · reviewed October 28, 2026.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.