Emmanuel Akinfulubi

JavaScriptArray

Run-length encode and decode an array in JavaScript

Advanced · 4 min read

Run-length encoding is one of the simplest ways to compress data. Instead of storing a, a, b, c, c, c, you store "two a's, one b, three c's". It is used in some image formats, where long stretches of the same color are common, and it is a popular interview question because it tests careful loop writing.

In this tutorial you will write encode, which turns ['a', 'a', 'b', 'c', 'c', 'c'] into [['a', 2], ['b', 1], ['c', 3]], and decode, which turns it back. Then you will make the familiar text form, 'a3b2c1'. You should know arrays, for...of loops and arrow functions.

Runs, not counts

A run is a stretch of equal values sitting next to each other. The word "next to" is the whole point. In ['a', 'b', 'a'] the letter a appears twice, but the two a's are not neighbors, so there are three runs: one a, one b, one a.

That makes this different from counting how often each value appears. Counting would say "a: 2, b: 1" and lose the order, so you could never rebuild the original list.

The plan

Walk through the values one at a time and keep a list of runs. For each value, look at the last run in the list:

  • If it holds the same value, add one to its count.
  • Otherwise, start a new run with a count of one.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

46 Run-length encode and decode

hard

Turn ['a', 'a', 'b', 'c', 'c', 'c'] into [['a', 2], ['b', 1], ['c', 3]], and write the decoder that reverses it. Non-adjacent repeats are separate runs.

Stuck? Three hints, smallest first
  1. 1. Compare each value with the last one you emitted: extend that run, or start a new one.
  2. 2. out.at(-1) gives you the run in progress, and you can increment its count in place.
  3. 3. Decoding is flatMap with Array(count).fill(value).

Step 1: look at the run in progress

at(-1) reads the last item of an array. On an empty array it returns undefined.

Step 1

const runs = [['a', 2]];
console.log(runs.at(-1)); // [ 'a', 2 ]
console.log([].at(-1));   // undefined

Each run is a pair, [value, count]. So current[0] is the value and current[1] is the count.

Step 2: extend a run or start one

Step 2

function encode(xs) {
  const runs = [];
  for (const v of xs) {
    const current = runs.at(-1);
    if (current !== undefined && current[0] === v) current[1] += 1;
    else runs.push([v, 1]);
  }
  return runs;
}

console.log(encode(['a', 'a', 'b', 'c', 'c', 'c'])); // [ [ 'a', 2 ], [ 'b', 1 ], [ 'c', 3 ] ]
console.log(encode(['a', 'b', 'a']));                // [ [ 'a', 1 ], [ 'b', 1 ], [ 'a', 1 ] ]
console.log(encode([]));                             // []

The check current !== undefined comes first, because on the very first value there is no run yet, and undefined[0] would throw an error. && stops as soon as the left side is false, so current[0] is only read when a run exists.

current[1] += 1 changes the count inside the pair that's already in runs. current is not a copy, it is the same pair, so the update shows up in the result.

Step 3: decode

Decoding turns each pair back into that many copies of the value. Array(n).fill(v) makes an array of length n filled with v:

JavaScript

console.log(Array(3).fill('c')); // [ 'c', 'c', 'c' ]

Each pair becomes an array, and we want one flat list at the end. flatMap does both: it maps each pair to an array, then joins those arrays together.

Step 3

const decode = (runs) => runs.flatMap(([v, n]) => Array(n).fill(v));

console.log(decode([['a', 2], ['b', 1], ['c', 3]])); // [ 'a', 'a', 'b', 'c', 'c', 'c' ]
console.log(decode([]));                             // []

([v, n]) unpacks each pair into its value and its count. With plain map instead, you would get three separate arrays inside an array.

Step 4: check the round trip

A good encoder and decoder undo each other. Decoding an encoding should give back exactly what you started with:

Step 4

function encode(xs) {
  const runs = [];
  for (const v of xs) {
    const current = runs.at(-1);
    if (current !== undefined && current[0] === v) current[1] += 1;
    else runs.push([v, 1]);
  }
  return runs;
}
const decode = (runs) => runs.flatMap(([v, n]) => Array(n).fill(v));
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);

const letters = ['a', 'a', 'b', 'c', 'c', 'c'];
console.log(same(decode(encode(letters)), letters)); // true

same compares two values by their JSON text. The exercise panel has it built in.

Step 5: the text form

Most people know run-length encoding as text like 'a3b2c1'. Split the string into letters with [...text], encode, then write each pair as letter plus count and join:

Step 5

function encode(xs) {
  const runs = [];
  for (const v of xs) {
    const current = runs.at(-1);
    if (current !== undefined && current[0] === v) current[1] += 1;
    else runs.push([v, 1]);
  }
  return runs;
}

const encodeText = (text) => encode([...text]).map(([c, n]) => c + n).join('');
console.log(encodeText('aaabbc')); // a3b2c1

c + n joins a letter and a number into text, so 'a' + 3 is 'a3'.

Step 6: what "the same" means

The loop compares with ===. That has two effects worth knowing:

Step 6

function encode(xs) {
  const runs = [];
  for (const v of xs) {
    const current = runs.at(-1);
    if (current !== undefined && current[0] === v) current[1] += 1;
    else runs.push([v, 1]);
  }
  return runs;
}

console.log(encode([1, '1']));            // [ [ 1, 1 ], [ '1', 1 ] ]
console.log(encode([NaN, NaN]).length);   // 2

The number 1 and the text '1' are different, so they get separate runs. And NaN === NaN is false in JavaScript, so two NaNs side by side become two runs of one. If you need NaN to match itself, compare with Object.is(current[0], v) instead.

Encoding doesn't always make data smaller, either. ['a', 'b', 'a'] turned into three pairs, which is more than the input. It only pays off when the runs are long.

The full solution

The panel has encode, decode and encodeText, checks the round trip, and ends with the 1 and '1' and NaN cases. Press Run and read each result.

The answer

function encode(xs) {
  const runs = [];
  for (const v of xs) {
    const current = runs.at(-1);
    if (current !== undefined && current[0] === v) current[1] += 1;
    else runs.push([v, 1]);
  }
  return runs;
}

const decode = (runs) => runs.flatMap(([v, n]) => Array(n).fill(v));

// The compact text form, which is what "RLE" usually means.
const encodeText = (text) => encode([...text]).map(([c, n]) => c + n).join('');

const letters = ['a', 'a', 'b', 'c', 'c', 'c'];

console.log('encode      :', encode(letters));
console.log('decode      :', decode(encode(letters)));
console.log('round trip  :', same(decode(encode(letters)), letters));
console.log('not adjacent:', encode(['a', 'b', 'a']), '<- three runs, not two');
console.log('text form   :', encodeText('aaabbc'));
console.log('--- === is the comparison, for better and worse ---');
console.log("[1, '1']    :", encode([1, '1']), '<- two runs');
console.log('[NaN, NaN]  :', encode([NaN, NaN]).length, 'runs, because NaN !== NaN');

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test("the example", encode(letters), [['a', 2], ['b', 1], ['c', 3]]);
test('decode is the exact inverse', decode(encode(letters)), letters);
test('a single element is a run of one', encode(['a']), [['a', 1]]);
test('an empty input encodes to nothing, and decodes back', [encode([]), decode([])], [[], []]);
test('a repeat that is not adjacent is a separate run', encode(['a', 'b', 'a']), [['a', 1], ['b', 1], ['a', 1]]);
test('numbers work the same way', encode([1, 1, 2]), [[1, 2], [2, 1]]);
test('=== means 1 and "1" never share a run', encode([1, '1']).length, 2);
test('and NaN never joins its own run', encode([NaN, NaN]).length, 2);
test('the text form is the familiar one', encodeText('aaabbc'), 'a3b2c1');

The whole algorithm is "compare with the previous element", and the only decision is what "the same" means. Using === gives you the NaN assertion above: two adjacent NaNs become two runs of one, because NaN !== NaN. If that matters, compare with Object.is instead — it treats NaN as equal to itself, and separates 0 from -0.

Note that encoding does not always shrink the data. ['a', 'b', 'a'] produces three pairs, which is bigger than the input. Run-length encoding only pays when runs are long, which is why it shows up in bitmap formats and almost nowhere else.

Common mistakes

  • Counting all occurrences instead of runs. ['a', 'b', 'a'] has three runs. A plain count loses the order and can't be decoded.
  • Reading current[0] before checking that a run exists. On the first value current is undefined, and reading from it throws.
  • Decoding with map instead of flatMap. You get an array of arrays, not the original flat list.

Try it yourself

  1. Write decodeText('a3b2c1') that turns the text form back into 'aaabbc'.
  2. Change encodeText so a run of one is written without a number, giving 'a3b2c'.
  3. Switch the comparison to Object.is and check that [NaN, NaN] becomes one run.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.