Start learning free

LESSON 159 OF 414 · LOOPING OVER ARRAY INDICES

Employee of the Year V5 - Project in TypeScript

Practice

Hand out bonuses to the top 2 most productive employees: the best one first, then the second best. You don't need any sorting. Find the best employee with the loop from v4, then find the best of the other employees with a second loop.

You start with:

const names: string[] = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"];
const productivities: number[] = [83, 133, 97, 150, 120];
const salaries: number[] = [135000, 335000, 210000, 250000, 180000];

Build:

Alice Chen: $37500
Mary Jane: $50250

Rules:

  • Index i in all three arrays refers to the same employee.
  • The best employee is the one with the highest productivity; the second best is the one with the highest productivity among all the other employees.
  • If two employees have the same productivity, the one listed first wins.
  • Each bonus is 15% of the salary, rounded down (with Math.floor).
  • Print two lines, the best employee first: name: $bonus.

Find the best employee first, exactly as in v4. Remember: strictly greater, so the first listed wins a tie.

For the second place, loop over all the indices and ignore the best one. The whole condition is if (i !== bestIndex && (secondIndex === -1 || productivities[i] > productivities[secondIndex])) {. "Nobody chosen yet" must also let an employee in.

const names: string[] = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"];
const productivities: number[] = [83, 133, 97, 150, 120];
const salaries: number[] = [135000, 335000, 210000, 250000, 180000];

let bestIndex: number = 0;
for (let i: number = 1; i < names.length; i++) {
    if (productivities[i] > productivities[bestIndex]) {
        bestIndex = i;
    }
}
let secondIndex: number = -1;
for (let i: number = 0; i < names.length; i++) {
    if (i !== bestIndex && (secondIndex === -1 || productivities[i] > productivities[secondIndex])) {
        secondIndex = i;
    }
}
const bestBonus: number = Math.floor(salaries[bestIndex] * 15 / 100);
const secondBonus: number = Math.floor(salaries[secondIndex] * 15 / 100);
console.log(names[bestIndex] + ": $" + bestBonus);
console.log(names[secondIndex] + ": $" + secondBonus);

STEP 1 OF 10
    Ctrl + Enter to check

    Employee Of The Year V5 in TypeScript

    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free