var total = [];
var ids = [10000, 14000, 19999];
for (var i = 0; i < 20000; i++) {
total.push({id: i, value: Math.floor(Math.random() * 1000)});
}
total.filter((item) => ids.includes(item.id));
ids.map((id) => total.find((item) => item.id === id)).filter((item) => !!item) ?? []
ids.map((id) => total.find((item) => item.id === id))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Filter | |
Find with default | |
Find without default |
Test name | Executions per second |
---|---|
Filter | 885.4 Ops/sec |
Find with default | 28988.6 Ops/sec |
Find without default | 29012.7 Ops/sec |
Let's dive into the provided benchmark.
Benchmark Overview
The benchmark compares three approaches to filter an array of objects in JavaScript:
Array.prototype.filter()
map()
followed by find()
with and without providing a default valuemap()
followed by find()
without providing a default valueThe benchmark generates a large dataset (20000 elements) and repeats the filtering process on this data using each of the three approaches.
What is tested?
Array.prototype.filter()
map()
followed by find()
with a default valuemap()
followed by find()
without providing a default valueOptions compared
Array.prototype.filter()
: This is the built-in JavaScript method for filtering arrays.map()
followed by find() with default value
: This approach uses map()
to create a new array with transformed elements, and then uses find()
to find the first element that satisfies the condition. The filter
function returns the first element or an empty array if no element is found.map()
followed by find()
without default value: This approach uses map()
to create a new array with transformed elements, and then uses find()
to find the first element that satisfies the condition.Pros and Cons
Array.prototype.filter()
: Pros:map()
followed by find()
with default value: Pros:filter()
map()
followed by find()
without default value: Pros:filter()
Library and syntax
The benchmark uses the following library:
The benchmark uses the following special JavaScript feature or syntax:
Alternative approaches
Other alternative approaches for filtering arrays in JavaScript include:
reduce()
with a predicate functionforEach()
and checking if an element was returned from the callback functionsome()
with a predicate functionEach of these approaches has its own trade-offs and may be more or less suitable depending on the specific use case.
In general, it's recommended to use Array.prototype.filter()
, as it is built-in, efficient, and clear in syntax. However, using map()
followed by find()
can provide additional benefits for functional programming styles or when working with large datasets.