Nested Array.som

Benchmark created on


Setup

const mockData = createMockData(30, 4);

function getId () {
	return 	Math.floor(Math.random() * 100)
}

function createMockData(itemCount, relationCount){
	const arr = []
	for(let i = 0; i < itemCount; ++i){
		const relations = []
		for(let j = 0; j < relationCount; j++){
			relations.push({nodeId: getId()})
		}
		arr.push({id: getId(), relations})		
	}
	return arr;
}

function getNodeIds(arr) {
  const idCollection = {};

  for (const item of arr) {
    const itemId = item.id;
    const hasItemIdInRelation = item.relations.some(relation => relation.nodeId === itemId);
    if (hasItemIdInRelation) {
      idCollection[itemId] = true;
    }
  }
  return idCollection;
}

const idCollection = getNodeIds(mockData);

console.log(mockData)
console.log(idCollection)

Test runner

Ready to run.

Testing in
TestOps/sec
Nested Array.some
function hasId(arr, targetId){
	return arr.some(item => {
		return item.id === targetId && item.relations.some(relation => relation.nodeId === targetId)
	})
}

hasId(mockData, 100);
ready
Array.map + Array.some
function hasId(idCollection, targetId) {
  return idCollection[targetId] !== undefined;
}

hasId(idCollection, 100);
ready

Revisions

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