JavaScript: Find N in a row


Problem

Given array:

const items = [0, 1, 1];

How can you identify if there are N items in a row?

Solution

To identify if there are 2 items in a row, iterate through the items and keep a count:

const N = 2;
let previous;
let count;

for (const item of items) {
  if (item === previous) {
    count++;
  } else {
    count = 1;
    previous = item;
  }

  if (count === N) {
    console.log(item);
    break;
  }
}

findNInARow

A function to return the array item if it repeats N times in a row:

/**
 * Find N in a row.
 *
 * @param {number} N
 * @param {any[]} items
 * @return {any}
 */
function findNInARow(N, items) {
  if (N < 1) {
    return;
  }

  if (items.length === 0) {
    return;
  }

  let previous = Symbol();
  let count = 0;

  for (const item of items) {
    if (item === previous) {
      count += 1;
    } else {
      count = 1;
      previous = item;
    }

    if (count === N) {
      return item;
    }
  }

  return;
}

Symbol() is used to generate a unique identifier since there’s no previous item when the loop first begins.

hasNInARow

A function to check if array has N items in a row:

/**
 * Has N in a row.
 *
 * @param {number} n
 * @param {any[]} items
 * @return {boolean}
 */
function hasNInARow(N, items) {
  if (N < 1) {
    return true;
  }

  if (items.length === 0) {
    return false;
  }

  let previous = Symbol();
  let count = 0;

  for (const item of items) {
    if (item === previous) {
      count += 1;
    } else {
      count = 1;
      previous = item;
    }

    if (count === N) {
      return true;
    }
  }

  return false;
}

Demo

Repl.it:



Please support this site and join our Discord!