JavaScript | reduce()函数|

这篇博客探讨了JavaScript中数组的reduce方法,包括不同初始值的使用情况,以及如何将二维数组转换为一维数组。此外,还展示了如何通过reduce统计数组元素出现的次数,并按对象的特定属性进行分类。
摘要由CSDN通过智能技术生成

// 初始值为0
let array = [1, 3, 5];
console.log(
  array.reduce((preValue, curValue, curIndex) => {
    console.log(curIndex + "--" + preValue + "--" + curValue);
    return preValue + curValue;
  }, 0)
);
// 初始值为10

console.log("1111111111111111111111111111111111111111111");
let array1 = [1, 3, 5];
console.log(
  array1.reduce((preValue, curValue, curIndex) => {
    console.log(curIndex + "--" + preValue + "--" + curValue);
    return preValue + curValue;
  }, 10)
);
// 没有初始值
console.log("22222222222222222222222222222222222222222222");
let array2 = [1, 3, 5];
console.log(
  array2.reduce((preValue, curValue, curIndex) => {
    console.log(curIndex + "--" + preValue + "--" + curValue);
    return preValue + curValue;
  })
);
// 二维数组变一维
console.log("333333333333333333333333333333333333333333333");
let array3 = [
  [0, 1],
  [2, 3],
  [4, 5],
];
console.log(
  array3.reduce((acc, cur) => {
    console.log("acc=", acc);
    console.log("cur=", cur);
    console.log("---------");
    return acc.concat(cur);
  }, [])
);
// 统计数组中元素次数
console.log("44444444444444444444444444444444444444");
const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];
let countedNames = names.reduce(function (allNames, name) {
  if (name in allNames) {
    allNames[name]++;
  } else {
    allNames[name] = 1;
  }
  return allNames;
}, {});

console.log(countedNames);
//按属性对object分类
console.log("55555555555555555555555555555555555555555555");
var people = [
  { name: "Alice", age: 21 },
  { name: "Max", age: 20 },
  { name: "Jane", age: 20 },
];

function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj, index) {
    var key = obj[property]; //=> key=21,20,20
    if (!acc[key]) {
      acc[key] = []; //分别对key为21和20的时候,初始化两个空数组,用来存放对象
    }
    acc[key].push(obj); //将符合key=21或20的对象压栈
    return acc;
  }, {});
}

var groupedPeople = groupBy(people, "age");
console.log(groupedPeople);



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值