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

Reducing multi-dimensional array that contains objects not integers

所以我有这个数组:

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

最终我想做的是遍历数组并累积循环值,直到找到匹配项。

所以我有这个代码:

    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;
    });

我得到了这个记录输出:

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

能减少不处理对象吗?我很困惑为什么它不能处理这个。是我做错了什么,还是 Array.prototype.reduce 只处理整数?

我认为只要我将对象映射到一个整数,它就可以处理对象"on the way out"。搞什么。

假设您希望通过逐步累积循环值达到的目标是 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

如果你想成为一名能手,你也可以像这样将 reduce 压缩成一行:

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