Remove repeated data (v3)

Revision 3 of this benchmark created on


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
for loop
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
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
Inplace
if (data.length) {
  let k = 0;
  let lastElement = data[0];
  for (let i = 1; i < data.length; 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.