JS 帮助理解 Reduce((countsMap, item) => countsMap.set(item, countsMap.get(item) + 1 || 1), new Map))

JS HELP to understand Reduce((countsMap, item) => countsMap.set(item, countsMap.get(item) + 1 || 1), new Map))

我有一个任务,我找到了一个完美的解决方案,虽然我不太明白它是如何工作的。谁能帮我详细解释一下?特别是这个(countsMap, item) => countsMap.set(item, countsMap.get(item) + 1 || 1)

 var testArray = ["dog", "dog", "cat", "buffalo", "wolf", "cat", "tiger", "cat"];
    function compressArray(original) {
        return array.reduce((countsMap, item) => countsMap.set(item, countsMap.get(item) + 1 || 1), new Map());
    }


console.log(compressArray(testArray));

reduce() 方法对累加器和数组中的每个元素(从左到右)应用函数以将其减少为单个值。

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

对于 => 调用的 箭头函数 ,它的工作方式类似于

(param1, param2, …, paramN) => { statements } 

var materials = ['Hydrogen', 'Helium', 'Lithium', 'Beryllium'];


console.log(materials.map((material) => {
  return material.length;
})); // [8, 6, 7, 9]

让我们把它分解成几个组成部分

const foo = countsMap.get(item); // get the value of key `item` from a Map
const bar = foo + 1 || 1; // Increment foo by 1, or start at 1
// n.b. this works because `undefined + 1; // NaN`, I would instead
// recommend `(foo || 0) + 1`
const baz = countsMap.set(item, bar); // set the value of key `item` to `bar`
// n.b. this is chainable (i.e. returns `countsMap`)
const fn = (x, y) => x + y; // a function which takes x and y, and returns their sum

// so finally,
const reducor = (countsMap, item) => countsMap.set(item, countsMap.get(item) + 1 || 1);
// 1. look up from map
// 2. increment 1, or start at 1
// 3. set back to map
// 4. return map

Array.prototype.reduce

我发现向某人表达这一点的最简单方法是手写

const arr = [1, 2, 3]; // some array
const sum = (accumilator, nextValue) => accumilator + nextValue; // some function
// n.b. the return value is the next accumilator
const initialValue = 0;
const result = arr.reduce(sum, initialValue); // 6, i.e. 1 + 2 + 3

那么这看起来像什么?在 for 循环中?

// lets start the same as before
const arr = [1, 2, 3];
const sum = (accumilator, nextValue) => accumilator + nextValue;

// now to calculate the result,
let accumilator = 0; // = initial value
for (let i = 0; i < arr.length; ++i) {
    const nextValue = arr[i];
    accumilator = sum(accumilator, nextValue);
}
accumilator; // 6
  • 您在数组 testArray 上使用了一个循环(但很奇特 - reduce)。
  • 在执行循环时,您使用一个对象(但很花哨 - 地图)来反映值在数组中被注意到的次数。
  • 你也用了箭头函数,所以语法简洁,不需要写return语句。