简体   繁体   English

减少包含对象而不是整数的多维数组

[英]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? 我在做错什么吗,还是Array.prototype.reduce仅处理整数?

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. 有没有搞错。

Supposing the target you want to hit by progressively accumulating cycle values is 15, you could do something like this: 假设您要通过逐步累积循环值来达到15个目标,则可以执行以下操作:

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: 如果您想成为热门人物,也可以将reduce压缩成这样的一行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM