Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
javascript array.filter faster alternative
Array.prototype.betterFilter = function(expression) {
	var res = [];
	for(var idx=0; idx<this.length; idx++){
		var currentItem = this[idx];
		if(expression(currentItem)){
			res.push(currentItem);
		}
	}
	return res;
};

Tests on node

Array length: 10

  • betterFilter: 0.166ms
  • filter: 0.280ms

Array length: 100

  • betterFilter: 0.149ms
  • filter: 0.346ms

Array length: 1000

  • betterFilter: 0.425ms
  • filter: 1.319ms

Array length: 5000

  • betterFilter: 0.745ms
  • filter: 4.394ms

Array length: 15520

  • betterFilter: 1.097ms
  • filter: 13.416ms

Tests made with comparison function

function(item){
	return item._id != '58e75e565b73626beffafdc0'
}

Tests made with Array of objects of type:

{
	"_id": "58e75e565b73626beffafdc0",
	"index": 0,
	"guid": "3612ccd3-dd2f-4107-819d-061980899495",
	"isActive": true,
	"balance": "$1,366.31",
	"picture": "http://placehold.it/32x32",
	"age": 20,
	"eyeColor": "brown",
	"name": "Carey Herrera",
	"gender": "female",
	"company": "XYMONK",
	"email": "careyherrera@xymonk.com",
	"phone": "+1 (923) 565-2098",
	"address": "609 Catherine Street, Marion, California, 5277",
	"about": "Culpa consectetur officia aliquip occaecat adipisicing ipsum id ea commodo voluptate ullamco dolor. Irure sint culpa amet laboris ex officia dolore aliqua adipisicing quis qui esse exercitation. Aute voluptate voluptate commodo est ipsum et consequat irure laboris. Labore veniam aute enim qui ea excepteur aute ut officia consectetur. Ad sint ad labore nisi dolor tempor veniam. Ea consequat sit Lorem eiusmod tempor ex aliqua mollit ipsum eiusmod aliquip exercitation incididunt.\r\n",
	"registered": "2017-01-31T03:45:54 -02:00",
	"latitude": -20.944402,
	"longitude": 179.241631,
	"tags": [
		"anim",
		"mollit",
		"nostrud",
		"labore",
		"magna",
		"adipisicing",
		"velit"
	],
	"friends": [
		{
			"id": 0,
			"name": "Blake Calderon"
		},
		{
			"id": 1,
			"name": "Ollie Lindsey"
		},
		{
			"id": 2,
			"name": "Byrd Peterson"
		}
	],
	"greeting": "Hello, Carey Herrera! You have 7 unread messages.",
	"favoriteFruit": "banana"
}

More tests (including browser tests) here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.