skip to Main Content

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": 1, "calculatedFee":  200, "feeNumber": 10, "group": "2"},
  { "bankNumber": 1, "calculatedFee":  20, "feeNumber": 10, "group": "2" },
  { "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 and bankNumber. For example calculatedFee = 0 is the smallest for group 1 and bankNumber 1, calculatedFee = 10 is the smallest for group 3 and bankNumber 2,. However, I have no idea what function to create in JavaScript to get such results

2

Answers


  1. Use Math.min() along with filter() and map()

    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": 1, "calculatedFee":  200, "feeNumber": 10, "group": "2"},
      { "bankNumber": 1, "calculatedFee":  20, "feeNumber": 10, "group": "2" },
      { "bankNumber": 2, "calculatedFee":  10, "feeNumber": 10, "group": "3" },
      { "bankNumber": 2, "calculatedFee": 100, "feeNumber": 10, "group": "3" },
      { "bankNumber": 3, "calculatedFee": 100, "feeNumber": 10, "group": "2" },
    ]
    
    const result = Math.min(...data.filter(i => i.group === '3' && i.bankNumber === 2).map(i => i.calculatedFee))
    
    console.log(result)
    Login or Signup to reply.
  2. You can use Array#reduce with an object to store the minimum fee for each combination of bankNumber and group.

    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:1,calculatedFee:200,feeNumber:10,group:"2"},{bankNumber:1,calculatedFee:20,feeNumber:10,group:"2"},{bankNumber:2,calculatedFee:10,feeNumber:10,group:"3"},{bankNumber:2,calculatedFee:100,feeNumber:10,group:"3"},{bankNumber:3,calculatedFee:100,feeNumber:10,group:"2"},];
    const res = data.reduce((acc, {bankNumber, group, calculatedFee}) => {
      (acc[bankNumber] ??= {})[group] = Math.min(acc[bankNumber][group] ?? Infinity, calculatedFee);
      return acc;
    }, {});
    for (const [bank, vals] of Object.entries(res)) 
      for (const [group, fee] of Object.entries(vals)) 
        console.log('Bank', bank, 'Group', group, 'Min fee', fee);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search