Start learning free

LESSON 184 OF 671 · LOOPING OVER ARRAY INDICES

Employee of the Year V5 in JavaScript: Top 2 Without Sorting

Practice Read the full explanation

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 = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"];
const productivities = [83, 133, 97, 150, 120];
const salaries = [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 = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"];
const productivities = [83, 133, 97, 150, 120];
const salaries = [135000, 335000, 210000, 250000, 180000];

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

STEP 1 OF 10
    Ctrl + Enter to check

    JAVASCRIPT · LOOPING OVER ARRAY INDICES

    Employee Of The Year V5 in JavaScript, explained

    Problem overview

    Version 4 found the single best employee with a loop. Version 5 hands out two bonuses: the most productive employee comes first, and the second most productive comes next. The data is the same three parallel arrays, names, productivities and salaries. Ties go to the employee listed first, and each bonus is 15% of the salary, rounded down. The program prints one line per employee in the form name: $bonus.

    Alice Chen: $37500
    Mary Jane: $50250
    

    Alice Chen (productivity 150) is first. Among the others, Mary Jane (133) is the best, so she is second.

    Approach

    The lesson avoids sorting. Sorting would reorder the productivities and lose the link to the names and salaries. Instead, the program runs two scans.

    The first scan is version 4's loop and gives bestIndex. The second scan looks for the best employee among everyone except bestIndex. It needs a starting value, but employee 0 might be the best employee, who is excluded. So the second scan starts with secondIndex = -1, which means nobody chosen yet. No array has an element at index -1, so the value can't be confused with a real employee. The check for -1 lets the first eligible employee in without a comparison.

    Step by step

    1. Find the best. Steps 1 to 3 are version 4: bestIndex starts at 0, a loop from 1 compares each productivity with the best so far, and a strictly greater one replaces it.
    2. Create secondIndex with let and give it -1.
    3. Start a second loop at 0. The best employee could be at any position, so every index is visited, and the best one is skipped inside the loop.
    4. Write the condition for the second place. The employee must not be the best (i !== bestIndex), and either nobody is chosen yet (secondIndex === -1) or this employee's productivity is strictly greater than the current second's. When all of that holds, set secondIndex to i.
    5. Compute the two bonuses, bestBonus and secondBonus, each with the same 15% formula and Math.floor, from the salary at its own index.
    6. Print two lines, best first, each as the name, ": $" and the bonus.

    The solution in JavaScript

    const names = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"];
    const productivities = [83, 133, 97, 150, 120];
    const salaries = [135000, 335000, 210000, 250000, 180000];
    
    let bestIndex = 0;
    for (let i = 1; i < names.length; i++) {
        if (productivities[i] > productivities[bestIndex]) {
            bestIndex = i;
        }
    }
    let secondIndex = -1;
    for (let i = 0; i < names.length; i++) {
        if (i !== bestIndex && (secondIndex === -1 || productivities[i] > productivities[secondIndex])) {
            secondIndex = i;
        }
    }
    const bestBonus = Math.floor(salaries[bestIndex] * 15 / 100);
    const secondBonus = Math.floor(salaries[secondIndex] * 15 / 100);
    console.log(names[bestIndex] + ": $" + bestBonus);
    console.log(names[secondIndex] + ": $" + secondBonus);
    

    The details:

    • !== is strict inequality and === is strict equality. They compare without converting types, which is the safe default.
    • The condition has the shape A && (B || C). The parentheses matter. Without them, && binds tighter than || and the best employee could slip in through the second branch.
    • The secondIndex === -1 test comes first in the parentheses. Once it is false, productivities[secondIndex] is a real element. Reading productivities[-1] gives undefined, not an error, and a comparison with undefined is always false. So the explicit test is what puts the first eligible employee in.
    • The two loops are independent. Each has its own let i, which exists only inside that loop.

    Complexity

    Time: O(n). Two passes over the employees, each doing constant work per element, cost 2n steps, which is O(n). Sorting would cost O(n log n) and would only be worth it for a long ranking. Space: O(1), since only a few variables are stored.

    Tracing the starter data

    The first loop ends with bestIndex = 3 (productivity 150). In the second loop, index 0 (83) is accepted because secondIndex is -1. Index 1 (133) beats 83 and replaces it. Index 2 (97) doesn't beat 133. Index 3 is skipped because it is the best. Index 4 (120) doesn't beat 133. So secondIndex = 1: Mary Jane, with a bonus of Math.floor(335000 * 15 / 100) = 50250.

    Edge cases and common mistakes

    • Not skipping the best employee. Without i !== bestIndex, the second scan finds the same employee again and prints them twice.
    • Ties. With productivities [90, 90, 80], the best is index 0 and the second is index 1. The strict comparison keeps the earlier of two equal candidates in each scan.
    • Starting secondIndex at 0. If employee 0 is the best, the second scan starts from the wrong person. The -1 marker avoids this.
    • Looping from 1 in the second scan. Employee 0 would never be considered for second place.
    • Fewer than two employees. With one employee, secondIndex stays -1, and names[-1] is undefined. The lesson's data always has at least two.

    Testing

    • Productivities [10, 30, 20] give the second place to index 2.
    • Productivities [30, 10, 20] make index 0 the best and index 2 the second.
    • Productivities [5, 5] give the first place to index 0 and the second to index 1.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free