Compare array-column search

Benchmark created on


Description

Loop thru column or convert to column in two-dimensional array to check for existing item?

Preparation HTML



Setup

var theArray = 
      [[4, 5, 7, 1, 2, 0, 8, 3, 9],
      [0, 2, 9, 5, 0, 0, 1, 7, 0],
      [1, 6, 8, 0, 7, 9, 5, 2, 4],
      [0, 7, 4, 6, 5, 3, 9, 8, 0],
      [5, 9, 0, 2, 0, 0, 7, 0, 0],
      [8, 0, 0, 4, 9, 7, 6, 0, 2],
      [6, 0, 1, 7, 3, 0, 0, 9, 8],
      [7, 0, 0, 9, 1, 0, 0, 6, 0],
      [9, 3, 5, 8, 0, 2, 4, 1, 7]];
      
var theTarget = 2;
// allways look in column 3

const arrayColumn = (arr, c) => arr.map(x => x[c]);

function isTargetThereForLoop(arr, target) {
	for (let i=0; i<9; i++) {
	if (arr[i][3] === target) {
		return true;
	}
}
return false;
}

function isTargetThereMap(arr, target) {
	return arrayColumn(arr, 3).includes(target);
}

// Transpose Matrix (change rows with columns)
function transposeMap(matrix) {
  return matrix[0].map((col, i) => matrix.map(row => row[i])); 
}

// Look for Target in transposed matrix-array
function isTargetThereTranspose(arr, target) {
	return isTargetThereMap(transposeMap(arr), target);
}

Test runner

Ready to run.

Testing in
TestOps/sec
For Loop
var forLoop = isTargetThereForLoop(theArray, theTarget);
ready
Map Column to Array
var maphas = isTargetThereMap(theArray, theTarget);
ready
Transpose Matrix and Map Column to Array
var transmap = isTargetThereTranspose(theArray, theTarget);
ready

Revisions

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