Get first and last item in array (v2)

Revision 2 of this benchmark created on


Description

Find most performant method

Setup

const arr = [3,2,1]

Test runner

Ready to run.

Testing in
TestOps/sec
array.length
function getFirstAndLastItems(arr) {
	return [
		arr[arr[0]],
		arr[arr.length - 1]
	]
}

getFirstAndLastItems(arr)
ready
array.shift() and array.pop()
function getFirstAndLastItems(arr) {
	return [
		arr.shift(),
		arr.pop()
	]
}

getFirstAndLastItems(arr)
ready
array.slice()
function getFirstAndLastItems(arr) {
	return [
		arr.slice(0,1),
		arr.slice(-1)
	]
}

getFirstAndLastItems(arr)
ready
array.filter()
function getFirstAndLastItems(arr) {
	return arr.filter((item, i) => {
		return (
			(i == 0) || (i == arr.length - 1)
		);
    })
}

getFirstAndLastItems(arr)
ready
spread operator
function getFirstAndLastItems(arr) {
	const [firstItem, ...rest] = arr;
	const lastItem = rest.pop();
	return [firstItem, lastItem]
}

getFirstAndLastItems(arr)
ready
array.at()
function getFirstAndLastItems(arr) {
	return [
		arr.at(0),
		arr.at(arr.length - 1)
	]
}

getFirstAndLastItems(arr)
ready

Revisions

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