Alexander Mills
Alexander Mills

Reputation: 100190

Reducing multi-dimensional array that contains objects not integers

So I have this array:

  levels: [
            {
                level: 3, cycles: 5
            },
            {
                level: 4, cycles: 7
            },
            {
                level: 2, cycles: 3
            },
            {
                level: 1, cycles: 2
            }
        ]

ultimately want I want to do is iterate through the array and accumulate the cycles value until I get a match.

So I have this code:

    var priority = 1;  //default priority is 1

    cycleNumber = ind % queue._priority.totalPriorityCycles;

    queue._priority.levels.reduce(function (a, b) {

        const lower = a.cycles;
        const upper = a.cycles + b.cycles;
        console.log('lower => ', lower);
        console.log('upper => ', upper);

        if (cycleNumber <= upper) {
            priority = b.level;  // i need a reference to b.level too!
        }
        return upper;
    });

and I get this logged output:

lower =>  7
upper =>  12
lower =>  undefined
upper =>  NaN
lower =>  undefined
upper =>  NaN

can reduce not handle objects? I am so confused as to why it can't handle this. Is there something I am doing wrong, or does Array.prototype.reduce only handle integers?

I thought it might be able to handle objects as long as I mapped the object to an integer "on the way out". What the heck.

Upvotes: 0

Views: 42

Answers (1)

bwobst
bwobst

Reputation: 351

Supposing the target you want to hit by progressively accumulating cycle values is 15, you could do something like this:

const target = 15;

const totalCycles = levels.reduce(function(total, level) {
  if (total < target) {
    return total + level.cycles;
  } else {
    return total;
  }
}, 0);

console.log(totalCycles); // => 15

If you want to be a hotshot you could also condense the reduce into one line like this:

const totalCycles = levels.reduce((total, level) => (total < target) ? total + level.cycles : total, 0);

Upvotes: 1

Related Questions