katalingua
katalingua

Reputation: 11

How to format 'for loop' to take on reduce()?

function validateLineup (lineup) {
    let sumSalary = 0

    for (let i = 0 ; i < lineup.length; i++) {
        sumSalary += lineup[i].salary
        if (sumSalary > 45000) {
            return false
        } 
    }
    return true
}
module.exports = validateLineup

What I'm working with^ and would like to format as ternary.
I attempted to format it as ternary but ended up with this and it's not passing tests:

let sumSalary = lineup.reduce(function(sum, salary){
    return sum + lineup[i].salary
}, 0)

Edit: I want to format this to take on reduce(). Sorry for the mix-up.

Upvotes: 1

Views: 65

Answers (3)

trincot
trincot

Reputation: 351128

The downside of reduce is that you loose the possibility to have an early exit. If your array has 1000 entries, and already the first value crosses the 45000 threshold, you'll still be locked into making those 999 other iterations, without any benefit.

If you're looking for an array function that does the job with the possibility for an early exit, then consider every:

function validateLineup (lineup) {
    return lineup.every(function({salary}) {
        return (this.sum += salary) <= 45000;
    }, { sum: 0 }); // use `this` for tracking the sum
}

let lineup = [{ salary: 30000}, { salary: 30000}, { salary: 30000}];
console.log("within limits? ", validateLineup(lineup));

Upvotes: 2

Michel Vorwieger
Michel Vorwieger

Reputation: 722

you forgot to change lineup in your reducer

function validateLineup(lineup) {
    let sumSalary = lineup.reduce(function(sum, current){
        return sum + current.salary
    }, 0)
    
    return sumSalary <= 45000
}

or if you want it really compact:

const validateLineup = lineup => lineup.reduce((sum, {salary}) => sum + salary, 0) <= 45000;

Upvotes: 1

SakoBu
SakoBu

Reputation: 4011

I think you're looking for this?

function validateLineup(lineup) {
  let sumSalary = lineup.reduce((acc, val) => acc + val.salary, 0);
  return sumSalary <= 45000
}

Upvotes: 1

Related Questions