arr = [{a: 1, b: 20}, {a: "c", b: 20}]
idx = arr.findIndex(o => o.a === 'c')
arr.splice(idx, 1)
arr = arr.filter(o => o.a !== 'c')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
findItem + splice | |
reassignement & filter |
Test name | Executions per second |
---|---|
findItem + splice | 1137923.1 Ops/sec |
reassignement & filter | 2148896.2 Ops/sec |
Let's break down the provided benchmark definition and test cases to understand what is being tested.
Benchmark Definition: The benchmark is testing two approaches for removing an item from an array of objects by property:
findIndex
and splice
: This approach involves finding the index of the item in the array using the findIndex
method, which returns the lowest index at which this value can be found in the array. Once the index is found, the splice
method is used to remove the item from the array.filter
and reassignment: This approach involves creating a new array that includes only the items that do not match the specified condition using the filter
method. The resulting filtered array is then reassigned back to the original variable.Options Compared: The benchmark is comparing the performance of these two approaches:
findItem & splice
: Uses findIndex
and splice
reassignement & filter
: Uses filter
and reassignmentPros and Cons:
findIndex
and splice
, which can be slower than a single method call.filter
.Library/Functionality Used: None of the provided benchmark test cases use any external libraries. However, they do utilize JavaScript's built-in methods:
findIndex
: Returns the lowest index at which this value can be found in the array.splice
: Removes the item at the specified index from the array.filter
: Creates a new array that includes only the items that pass the test.Special JS Feature/Syntax:
The benchmark uses a feature of JavaScript called "Arrow Functions" (o => o.a === 'c'
), which is used as the callback function in the findIndex
and filter
methods. Arrow functions are a concise way to define small, single-expression functions. They were introduced in ECMAScript 2015 (ES6) and provide a more concise syntax for defining functions.
Alternatives: Other alternatives for removing an item from an array of objects by property could include:
map
and then slicing the resulting arrayforEach
and pushing or splicing the result into a new arrayfilterBy
method for filtering arraysIt's worth noting that the best approach will depend on the specific use case and performance requirements.