Checking if a value exists in a list of values

Benchmark created on


Setup

let foundKeys = ['foo', 'bar', '', '', 'zar'];
const keys = ['foo', 'bar']; 

Test runner

Ready to run.

Testing in
TestOps/sec
Multiple array functions
			foundKeys = foundKeys
				.filter((key) => key !== '')
				.map((key) => key.replace('$', ''));

			const safe = foundKeys
				.every((foundKey) => keys.includes(foundKey));
				
			const brokenKeys = foundKeys.filter((foundKey) => !keys.includes(foundKey));
ready
A forEach and includes
const brokenKeys = [];
let safe = true;

foundKeys.forEach((key) =>
{
	if(!key) return;
	key = key.replace('$', '');
	const isIncluded = keys.includes(key);
	safe = safe && isIncluded;
	
	if(!isIncluded) brokenKeys.push(key);
});
ready
A forEach and Set
const keysSet = new Set(keys);
const brokenKeys = [];
let safe = true;

foundKeys.forEach((key) =>
{
	if(!key) return;
	key = key.replace('$', '');
	const isIncluded = keysSet.has(key);
	safe = safe && isIncluded;
	
	if(!isIncluded) brokenKeys.push(key);
});
ready
A forEach and reduce
const keysSet = keys.reduce((set, key) =>
{
  set[key] = true;
  return set;
}, {});
const brokenKeys = [];
let safe = true;

foundKeys.forEach((key) =>
{
	if(!key) return;
	key = key.replace('$', '');
	const isIncluded = !!keysSet[key];
	safe = safe && isIncluded;
	
	if(!isIncluded) brokenKeys.push(key);
});
ready

Revisions

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