Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
Javascript - best logic/performance-wise for subtract total from Array of Objects

I am trying to think of a better way for this logic. Basically, I have 3 Tiers. Each tier has a limit number. E.g:

For tier 1, the limit is 5 For tier 2, the limit is 8 For Tier 3, the limit is 15.

[
            { title: 'Tier I', amount: 5, fullfiled: x, price: 10 },
            { title: 'Tier II', amount: 8, fullfiled: y, price: 20 },
            { title: 'Tier III', amount: 15, fullfiled: z, price: 30 },
]

What comes from my backend is the Total only. So let's suppose it returns 10. I need to get the difference to identify in which tier the user is. In this case, Tier 2, because for tier 1, the limit of 5 will be fulfilled. For Tier 2, only 5 / 8 will be fulfilled, therefore Y will be 3 as shown below:

I need to get the difference between these limits so that I can replace X, Y and Z with the number. I'd like a suggestion for an elegant way to solve this problem. I tried to have an array with the limits and subtract to get the difference. E.g:

let totalCompleted = 10;
const limitTier = [5, 8, 15] 

limitTier.map(value => {
   // logic ? totalCompleted - value;
})

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Try using a reducer rather than a map.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Something similar to this:

const { tiers } = [
  { title: 'Tier I', amount: 5, price: 10 },
  { title: 'Tier II', amount: 8,  price: 20 },
  { title: 'Tier III', amount: 15,  price: 30 },
].reduce(({ rest, tiers } , tier) => ({
  rest: Math.max(rest - tier.amount, 0),
  tiers: [
    ...tiers,
    {
      ...tier,
      fullfiled: Math.min(tier.amount, rest),
    }
  ]
}), { rest: 10, tiers: [] })
about 4 years ago · Juan Pablo Isaza Report

0

Try this solution.

const tiers = [
  { title: 'Tier I', amount: 5, fullfiled: 'x', price: 10 },
  { title: 'Tier II', amount: 8, fullfiled: 'y', price: 20 },
  { title: 'Tier III', amount: 15, fullfiled: 'z', price: 30 },
];

let totalCompleted = 10;

for (let item of tiers) {
  totalCompleted -= item.amount;
  if (totalCompleted < 0) {
    item.fullfiled = totalCompleted * -1;
    break;
  }
}
console.log('tier', tiers);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!