reduce()使用场景、用法总结

先来看MDN上的解释:

reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。

举个栗子:

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

reducer 函数接收4个参数:

Accumulator (acc) (累计器)
Current Value (cur) (当前值)
Current Index (idx) (当前索引)
Source Array (src) (源数组)

您的 reducer 函数的返回值分配给累计器,该返回值在数组的每个迭代中被记住,并最后成为最终的单个结果值。

接下来写写reduce的应用场景吧

数组求和:

var total=[ 0, 1, 2, 3 ].reduce((acc,cur)=> acc +cur,0);

累加对象数组里的值:

var initialValue = 0;
var sum = [{x: 1}, {x:2}, {x:3}].reduce(
    (accumulator, currentValue) => accumulator + currentValue.x
    ,initialValue
);

console.log(sum) // logs 6

// 函数形式:
var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) {
    return accumulator + currentValue.x;
},initialValue)

将二维数组转化为一维:

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  function(a, b) {
    return a.concat(b);
  },
  []  // 初始值
);

// flattened is [0, 1, 2, 3, 4, 5]
//你也可以写成箭头函数的形式:

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
 ( acc, cur ) => acc.concat(cur),
 []
);

计算数组中每个元素出现的次数:

var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

var countedNames = names.reduce(function (allNames, name) {
  if (name in allNames) {
    allNames[name]++;
  }
  else {
    allNames[name] = 1;
  }
  return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

按属性对object分类:

var people = [
  { name: 'Alice', age: 21 },
  { name: 'Max', age: 20 },
  { name: 'Jane', age: 20 }
];

function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    var key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
}

var groupedPeople = groupBy(people, 'age');
// groupedPeople is:
// {
//   20: [
//     { name: 'Max', age: 20 },
//     { name: 'Jane', age: 20 }
//   ],
//   21: [{ name: 'Alice', age: 21 }]
// }

数组去重:

let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
let myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
  if (accumulator.indexOf(currentValue) === -1) {
    accumulator.push(currentValue)
  }
  return accumulator
}, [])

console.log(myOrderedArray)

let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
let result = arr.sort().reduce((init, current) => {
    if(init.length === 0 || init[init.length-1] !== current) {
        init.push(current);
    }
    return init;
}, []);
console.log(result); //[1,2,3,4,5]
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaScript 中的数组方法有很多,每个方法都有各自的使用场景。以下是一些常见的数组方法及其使用场景: 1. `push()`:向数组末尾添加一个或多个元素。 使用场景:需要动态向数组中添加元素时。 2. `pop()`:从数组末尾删除一个元素。 使用场景:需要删除数组中最后一个元素时。 3. `unshift()`:向数组开头添加一个或多个元素。 使用场景:需要动态向数组开头添加元素时。 4. `shift()`:从数组开头删除一个元素。 使用场景:需要删除数组中第一个元素时。 5. `splice()`:删除、插入或替换数组中的元素。 使用场景:需要对数组进行复杂的操作时,如删除、插入或替换数组中的元素。 6. `slice()`:截取数组中的一部分元素,返回一个新数组。 使用场景:需要从数组中获取一个子集时,但不想修改原数组。 7. `concat()`:将多个数组合并成一个新数组。 使用场景:需要将两个或多个数组合并为一个数组时。 8. `join()`:将数组中的所有元素连接成一个字符串。 使用场景:需要将数组中的元素以特定的方式连接起来时。 9. `indexOf()`:查找数组中某个元素的位置。 使用场景:需要查找数组中某个元素的位置时。 10. `filter()`:返回符合条件的元素组成的新数组。 使用场景:需要筛选数组中符合某些条件的元素时。 11. `map()`:返回对每个元素进行操作后的数组。 使用场景:需要对数组中的每个元素进行操作并返回一个新数组时。 12. `reduce()`:使用指定的函数将数组中的元素合并为一个值。 使用场景:需要将数组中的元素合并为一个值时,如求和、求乘积等。 以上是一些常见的数组方法及其使用场景,当然还有其他的数组方法,具体使用场景还需根据实际情况进行选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值