Array.reduce vs Array.sort

Benchmark created on


Preparation HTML

<div id="result"></div>

Setup

const div = document.getElementById('result');

const testArray = [];
for(let i = 0; i < 100000; i++) {
	const newObject = {
		id: `${i}`,
		num: Math.floor(Math.random() * 100000)
	}
	testArray.push(newObject);
} 

Test runner

Ready to run.

Testing in
TestOps/sec
Array.sort()
testArray.sort((a, b) => b.num - a.num);

div.innerHTML = testArray[0]['id'];
ready
Array.reduce
const initialValue = {
	id: '-1',
	num: -Infinity
}

const maxValue = testArray.reduce((a, b) => b.num > a.num ? b : a, initialValue)

div.innerHTML = maxValue['id'];
ready

Revisions

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