Remove repeated data (v5)

Revision 5 of this benchmark created on


Description

Remove any int that is repeated as the next item. Data is an array of 10000 random ints between 0 and 9

Setup

const generateRandomNumbers = (size, max) => Array.from({ length: size }, () => Math.floor(Math.random() * (max + 1)));

const data = generateRandomNumbers(10000, 9);


Test runner

Ready to run.

Testing in
TestOps/sec
mplungjan: For loop with cached length
const removeRepeated = (data) => {
  const result = [];
  for (let i = 0, len = data.length; i < len; i++) {
    if (i === 0 || data[i] !== data[i - 1]) {
      result.push(data[i]);
    }
  }
  return result;
};

const result = removeRepeated(data);
ready
Alexander: Filter
const result = data.filter((item, idx, arr) => !idx || item !== arr[idx - 1]);
ready
Author's code with guard
if (data.length) {
  const result = [data[0]];
  let lastElement = data[0];
  for (let i = 1, n = data.length; i < n; ++i) {
    if (data[i] !== lastElement) {
      lastElement = data[i];
      result.push(lastElement);
    }
  }
}
ready
Trincot: Inplace
if (data.length) {
  let k = 0;
  let lastElement = data[0];
  for (let i = 1, n = data.length; i < n; i++) {
    if (data[i] !== lastElement) {
      lastElement = data[++k] = data[i];
    }
  }
  data.length = k + 1;
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.