reduce()方法

目录

参数

1. 数组求和、求乘积、求平均数、求最大,最小值

2. 累加数组中对象的值

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

4. 数组去重

5. 二维数组变一维数组

6. 将多维数组转化为一维

7. 根据属性把对象分类

8. 将数组转换为对象

9.   将对象转换为数组

10.  按条件分组

11.  将多数组合并为一个对象

12.  将字符串转化为对象

13. 检查字符串是不是回文字符


 

参数

参数描述
total必需。initialValue,或函数先前返回的值。
currentValue必需。当前元素的值。
index 可选。当前元素的数组索引。
arr  可选。当前元素所属的数组对象
initialValue

可选。作为初始值传递给函数的值。

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

注释:对没有值的数组元素,不执行 reduce() 方法。
注释:reduce() 方法不会改变原始数组。

1. 数组求和、求乘积、求平均数、求最大,最小值

// 求和
const num = [1, 2, 3, 4, 5]
const result1 = num.reduce((sum, n) => sum + n, 0)
console.log(result1); // 15
 
// 求乘积
// const result2 = num.reduce((sum, n) => sum * n)
const result2 = num.reduce((sum, n) => sum * n, 1)
console.log(result2); // 120

// 求平均数
const num = [1, 2, 3, 4, 5]
const result3 = num.reduce((sum, n) => sum + n, 0)/num.length
console.log(result3); // 3

// 求最大,最小值
const num = [1, 2, 3, 4, 5];
const max = num.reduce((acc, cur) => Math.max(acc, cur));
console.log(max); // 5
const min = num.reduce((acc, cur) => Math.min(acc, cur));
console.log(min); // 1

2. 累加数组中对象的值

let numObj = [{n: 1}, {n: 2}, {n: 3}, {n: 4}, {n: 5}]
let result3 = numObj.reduce((sum, obj) => sum + obj.n, 0)
console.log(result3); // 15

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

let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple', 'red']
let countColor = colors.reduce(function(all, color){
    if(color in all) {
        all[color]++;
    } else {
        all[color] = 1;
    }
    return all;
}, {});
console.log(countColor); // {blue: 1, green: 1, indigo: 1, orange: 1, purple: 1, red: 2, yellow: 1}



let arr = ['a', 'b', 'c', 'a', 'b'];
let count = arr.reduce((obj, item) => {
  // 如果对象中已经有了这个键,就让它的值加一
  if (obj[item]) {
    obj[item]++;
  } else {
    // 如果对象中没有这个键,就初始化为一
    obj[item] = 1;
  }
  // 返回对象作为下一次的累计值
  return obj;
}, {}); // 初始值为空对象
console.log(count); // {a: 2, b: 2, c: 1}

4. 数组去重

let arr = [1, 2, 3, 4, 4, 1]
let newArr = arr.reduce((pre,cur)=>{
    if(!pre.includes(cur)){
        return pre.concat(cur)
    }else{
        return pre
    }
},[])
console.log(newArr); // [1, 2, 3, 4]

5. 二维数组变一维数组

let twoArray = [[0, 1], [2, 3], [4, 5]]
let oneArray = twoArray.reduce((arr, val) => arr.concat(val), [])
console.log(oneArray);  // [0, 1, 2, 3, 4, 5]

6. 将多维数组转化为一维

let moreArr = [[0, 1], [2, 3], [4,[5,6,7]]]
const resultArr = function(moreArr){
      return moreArr.reduce((pre,cur) => pre.concat(Array.isArray(cur) ? resultArr(cur) : cur), [])
}
console.log(resultArr(moreArr)); // [0, 1, 2, 3, 4, 5, 6, 7]

7. 根据属性把对象分类

let peopleInfo = [
    {name: 'aaa', age: 15, sex: '男'},
    {name: 'bbb', age: 16, sex: '女'},
    {name: 'ccc', age: 15, sex: '女'}
]
function groupBy(objectArray, property) {
    return objectArray.reduce((resultObj, obj) => {
        var key = obj[property]
        if(!resultObj[key]) {
        	resultObj[key] = []
        }
        resultObj[key].push(obj)
        return resultObj;
    }, {})
}
let peopleAgeGroup = groupBy(peopleInfo, 'age')
console.log(peopleAgeGroup); // {15: [{name: "aaa", age: 15, sex: "男"}, {name: "ccc", age: 15, sex: "女"}],16: [{name: "bbb", age: 16, sex: "女"}]}
let peopleSexGroup = groupBy(peopleInfo, 'sex')
console.log(peopleSexGroup); // {男: [{name: "aaa", age: 15, sex: "男"}], 女: [{name: "bbb", age: 16, sex: "女"}, {name: "ccc", age: 15, sex: "女"}]}

 

 8. 将数组转换为对象

const entries = [['name', 'Alice'], ['age', 18], ['gender', 'female']];
const obj = entries.reduce((acc, cur) => {
  acc[cur[0]] = cur[1];
  return acc;
}, {});
console.log(obj); // {name: "Alice", age: 18, gender: "female"}

 

9.   将对象转换为数组

const obj = {
  name: 'Alice',
  age: 25,
  gender: 'female'
};

const arr = Object.keys(obj).reduce((acc, key) => {
  acc.push([key, obj[key]]);
  return acc;
}, []);

console.log(arr); // [['name', 'Alice'], ['age', 25], ['gender', 'female']]

10.  按条件分组

      假设我们有一个包含学生信息的数组,每个对象都有name和score属性,我们想要按照score是否大于等于60来分组,即及格和不及格。我们可以使用reduce这样做:  

// 定义一个学生数组
const students = [
  {name: 'Alice', score: 75},
  {name: 'Bob', score: 59},
  {name: 'Charlie', score: 82},
  {name: 'David', score: 48},
  {name: 'Eve', score: 66}
];

// 使用reduce按条件分组
const groups = students.reduce((acc, cur) => {
  // 判断当前对象的score是否大于等于60
  const key = cur.score >= 60 ? 'pass' : 'fail';
  // 如果累积对象中还没有这个key,就创建一个空数组
  if (!acc[key]) {
    acc[key] = [];
  }
  // 将当前对象推入对应的数组
  acc[key].push(cur);
  // 返回累积对象
  return acc;
}, {}); // 初始值为一个空对象

// 打印结果
console.log(groups);
/*
{
  pass: [
    { name: 'Alice', score: 75 },
    { name: 'Charlie', score: 82 },
    { name: 'Eve', score: 66 }
  ],
  fail: [
    { name: 'Bob', score: 59 },
    { name: 'David', score: 48 }
  ]
}
*/

 11.  将多数组合并为一个对象

        将多个数组合并为一个对象(下面示例最终展示结果有层级)

        要实现这个功能,我们可以使用reduce方法的第二个参数,即初始值。初始值可以是任何类型的值,包括一个空对象。然后,在reduce方法的回调函数中,我们可以根据数组元素的某个属性(例如用户ID)来判断是否已经存在对应的对象属性。如果不存在,就创建一个新的属性,并将数组元素赋值给它。如果存在,就将数组元素追加到已有的属性中。最后,返回累积的对象作为下一次迭代的初始值。

// 用户信息数组
const users = [
{ id: 1, name: "Alice", age: 25 },
{ id: 2, name: "Bob", age: 30 },
{ id: 3, name: "Charlie", age: 35 },
];

// 用户订单数组
const orders = [
{ id: 1, userId: 2, product: "Book", price: 10 },
{ id: 2, userId: 1, product: "Pen", price: 5 },
{ id: 3, userId: 3, product: "Shirt", price: 20 },
{ id: 4, userId: 2, product: "Shoes", price: 15 },
];

// 使用reduce方法将两个数组合并为一个对象
const result = users.reduce((acc, cur) => {

if (!acc[cur.id]) {   // acc初始是空{},要把users数组中的值存到acc中,比如第一次cur为users的第一条数据,cur.id=1,acc[1]=underfined,因为再空{}里找不到索引1的,!underfined = true      判断是否已经存在对应用户ID的属性
  
  acc[cur.id] = cur;  // 如果不存在,创建一个新的属性,并将用户信息赋值给它
      console.log(acc, 'acc1') // 1: {id: 1, name: "Alice", age: 25}
  acc[cur.id].orders = []; // 同时,创建一个空数组用来存储用户订单
    console.log(acc, 'acc2') // 1: {id: 1, name: "Alice", age: 25, orders:Array(0)}
}

for (let item of orders) {   // 遍历订单数组,找到属于当前用户的订单
  if (item.userId === cur.id) {
    
    acc[cur.id].orders.push(item); // 将订单追加到用户订单数组中
  }
}
 
return acc;  // 返回累积的对象
}, {}); // 初始值为空对象

// 打印结果
console.log(result);

c4f829547fbd4a6f9da0ccf6431529aa.png

427c626095fe4fe1a1885171b6d689de.png

2ed6af6c64c9499ab38d4d51903bdbee.png

 12.  将字符串转化为对象

        经常会遇到在url上进行取值,当然这有很多种方法,我们用reduce方法来实现。

// 将URL参数转化为对象
let url = "https://www.example.com?name=Tom&age=20&gender=male";
let params = url.split("?")[1]; // 获取参数部分
let obj = params.split("&").reduce((acc, cur) => {
  let [key, value] = cur.split("="); // 分割键和值
  acc[key] = value; // 将键和值添加到对象中
  return acc;
}, {}); // 初始值为空对象
console.log(obj); // {name: "Tom", age: "20", gender: "male"}

 13. 检查字符串是不是回文字符

        如果我们想要检查一个字符串是否是回文字符串,即正着读和反着读都一样

        首先,我们将字符串转换为数组,然后使用reduce方法从右到左遍历数组,将每个元素拼接到累积器上,得到一个反转后的字符串。然后,我们将反转后的字符串和原始字符串进行比较,如果相等,则说明是回文字符串,否则不是。

例如,给定字符串"racecar",我们可以这样写:

const isPalindrome = str => {
  // 将字符串转换为数组
  const arr = str.split('');
  // 使用reduce方法从右到左遍历数组,将每个元素拼接到累积器上
  const reversedStr = arr.reduce((accumulator, currentValue) => currentValue + accumulator, '');
  // 将反转后的字符串和原始字符串进行比较
  return reversedStr === str;
};

console.log(isPalindrome('racecar')); // true
console.log(isPalindrome('hello')); // false



// 或者这样写:
const fun = str => {
    let result = str.split('').reverse().toString().replaceAll(',','')
    return result === str
}
console.log(fun('abcd'))    // false
console.log(fun('abba'))    // true

 http://t.csdnimg.cn/Oe0x4

这个博主: 

 https://www.cnblogs.com/L-hailong/p/17637128.html

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值