Javascript 减少累加器解释

标签 javascript for-loop reduce accumulator

谁能用简单的英语解释一下下面的累加器acc结构?

return arr1.reduce(function(acc, curr){  
      var last = acc[acc.length-1];  
        if(acc.length > 0 && curr[1]===last[1]) {
        last[0] += curr[0];
      } else acc.push(curr);
      return acc;
      }, []);
    }

reduce 方法可用于解决 FreeCodeCamp“库存更新”作业,作为其高级算法脚本类(class)的一部分。

需要用“新交付”数组中的新商品更新库存数组 (arr1) 中的现有商品。

两个测试阵列,分别是当前库存curInv和新交货newInv,可能如下:

var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"]
];

var newInv = [
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]
];

在找到几篇关于 Javascript reduce 方法的优秀文章(例如 this post 和 Egghead.io 上的精彩视频类(class)),并以某种方式感知到它所消耗的力量之后,我会阅读该方法如下:

Reduce the inventory array, by creating an empty array [ ] first (the initial value), then applying the following callback function:

If the inventory array is currently not empty (has a length greater than zero), and the name of currently handled item (index 0 of curr could read "Bowling Ball" for example) is identical to the last item of the inventory array being updated, then update the amount of this item in the inventory array.

The last item is defined right above the if statement, as follows: take the present length of the accumulated array upto now, subtract 1, and use this value to index the accumulated array. The element at that index is then assigned to the variable 'last'.

On the other hand, if the inventory is empty, add the new item entirely, - that is: item name and amount. Now return the newly accumulated array."*

How is using the length - 1 of the accumulator useful to make acc actually accumulate? (pardon the alliteration)

我想我大部分都明白这个reduce方法是如何构建的,但是请纠正我的任何误读),除了这个特定的 使用acc.length-1

干杯,k。

最佳答案

实际的解决方案涉及对两个数组进行连接和排序,然后再减少它们。 在这种情况下,每当我们评估一个新项目时,如果它的名称不等于最后一个累加器项目,则意味着它是一个新项目。

使用您的示例,我们要减少的列表是:

[
  [ 21, 'Bowling Ball' ],
  [ 67, 'Bowling Ball' ],
  [ 2, 'Dirty Sock' ],
  [ 1, 'Hair Pin' ],
  [ 2, 'Hair Pin' ],
  [ 3, 'Half-Eaten Apple' ],
  [ 5, 'Microphone' ],
  [ 7, 'Toothpaste' ]
]

因此,当我们遇到第二项时,累加器中的最后一个值为[21, 'Boweling Ball'],当我们比较字符串时,我们进入第一个条件。

关于Javascript 减少累加器解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45695778/

相关文章:

c - 设置循环次数

javascript - 当循环遍历 JS 数组的值并删除值时,是否需要使用 while 而不是 for?

javascript - 如何过滤和映射嵌套数组项,同时检查要过滤的项是否满足某些条件?

javascript - 没有 JS/JQuery 的 ASP.NET

javascript - 使用 redux 依赖项发送 React 包

java - 嵌套 for 循环在两个字符串之间迭代

python - 如何使用 map、reduce、apply 或 python 中的其他函数(在本例中)转换 DataFrame?

haskell - 使用折叠组合 monad Action

javascript - 如何在 JavaScript 中映射 "map"的键/值对?

javascript - 定义这些对象有什么区别?