Home > Net >  Calculate completed percentage
Calculate completed percentage

Time:02-18

I have an array of different progress statuses and the current status. I want to be able to display the completed percentage. So far I have this:

    getCompletedPercentage(): Status | undefined | number {
        const index = this.statuses.findIndex(status => status.id === this.currentStatus?.id)
        const percentage = 100 * (index / this.statuses.length)
        return percentage
    },

this.statuses is an array of the different possible status (they all also have id's starting from 1). this.currentStatus is the current status of course :)

So let's say the statuses array has 6 different statuses and the current status is 3, I want to be able to display 50% completed. With the computed above I don't get 100% when the currentStatus is the last status. It starts off at 0 on the first one and then it increases but it's still only 85 when I'm on the last one. It's probably just something easy I'm missing but can't figure it out :)

CodePudding user response:

Array indexes are zero-based. So, the highest value for index is 5 (for a 6-item array). Modify your code like so:

getCompletedPercentage(): Status | undefined | number {
        const index = this.statuses.findIndex(status => status.id === this.currentStatus?.id)
        const percentage = 100 * index / (this.statuses.length - 1)
        return percentage
    }

A caveat you should be aware of is that this runs into trouble if the length of the array is one or less, you'll have inconsistent results. So you could try: const percentage = 100 * index / Math.max(this.statuses.length - 1, 1)

CodePudding user response:

You can achieve the requirement with this simple logic. Instead of index you can use the status ID as it starts from 1.

// Input statuses array
let statuses = [{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}];

// current status obect
const currentStatus = {id: 3};

// filtered object by using array.find() method to get the current status id.
const filteredObjId = statuses.find(status => status.id === currentStatus.id).id;

// Calculating the percentage
const percentage = 100 * (filteredObjId / statuses.length)

// Result
console.log(percentage);

I just added the JavaScript code snippet just to show the demo. You can use same logic in your typescript code.

  • Related