Finding indexes of elements (v6)

Revision 6 of this benchmark created on


Setup

const updatedRows = Array.from({ length: 5_000 }, (_, i) => i + 900_000 + 1);
const rows = Array.from({ length: 1_000_000 }, (_, i) => i + 1);

Test runner

Ready to run.

Testing in
TestOps/sec
Using indexOf
const result = updatedRows.map(
  (row) => rows.indexOf(row)
).filter((i) => i !== -1);

console.log(result);
ready
Using Map
const rowsMap = new Map(rows.map((row, index) => [row, index]));

const result = updatedRows
      .map(row => rowsMap.get(row))
      .filter((index) => index !== undefined);

console.log(result);
ready
Using Map efficient
const rowIndexMap = new Map();
  // Fill the map with row values and their corresponding indexes
  rows.forEach((row, index) => {
    rowIndexMap.set(row, index);
  });
  // Map updatedRows to their indexes in rows using the map
const result = updatedRows
  .reduce((acc, row) => {
  	const r = rowIndexMap.get(row);
  	if (r) {
  		acc.push(r);
  	}
  	return acc;
  }, []);

console.log(result);
ready

Revisions

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