I have array with objects
const data = [
{ "bankNumber": 1, "calculatedFee": 0, "feeNumber": 4, "group": "1" },
{ "bankNumber": 1, "calculatedFee": 147, "feeNumber": 6, "group": "1" },
{ "bankNumber": 1, "calculatedFee": 20, "feeNumber": 10, "group": "1" },
{ "bankNumber": 2, "calculatedFee": 10, "feeNumber": 10, "group": "3" },
{ "bankNumber": 2, "calculatedFee": 100, "feeNumber": 10, "group": "3" },
{ "bankNumber": 3, "calculatedFee": 100, "feeNumber": 10, "group": "2" },
]
I would like to filter this data to get the smallest value calculatedFee
with one group
. For example calculatedFee
= 0
is the smallest for group
1
, calculatedFee
= 10
is the smallest for group
3
. However, I have no idea what function to create in JavaScript to get such results
2
Answers
You can use a standard ‘group-by’ checking on each iteration if the current
calculatedFee
is less than the previously stored value for the group orInfinity
if the group isn’t stored yet.You can accomplish this through the union of Array.prototype.reduce and Array.prototype.filter in JavaScript.
Here’s a function that will carry out the task:
This function initially calculates the minimum
calculatedFee
for eachgroup
and stores them within theminFeesByGroup
object. Then it filters the original array to solely incorporate those objects where thecalculatedFee
coincides with the minimum for its group.