经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Java » 查看文章
JavaScript数组对象高阶函数reduce的妙用详解
来源:jb51  时间:2023/4/21 8:57:19  对本文有异议

reduce 是 JavaScript 数组对象上的一个高阶函数

它可以用来迭代数组中的所有元素,并返回一个单一的值。

其常用的语法为: array.reduce(callback[, initialValue])

其中,callback 是一个回调函数,它接受四个参数:累加器(初始值或上一次回调函数的返回值)、当前元素、当前索引、操作的数组本身。initialValue 是一个可选的初始值,如果提供了该值,则作为累加器的初始值,否则累加器的初始值为数组的第一个元素。 reduce 函数会从数组的第一个元素开始,依次对数组中的每个元素执行回调函数。回调函数的返回值将成为下一次回调函数的第一个参数(累加器)。最后,reduce 函数返回最终的累加结果。 以下是一个简单的 reduce 示例,用于计算数组中所有元素的和:

  1. const arr = [1, 2, 3, 4, 5];
  2. const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue);
  3. console.log(sum); // 15

在上面的代码中,reduce 函数从数组的第一个元素开始,计算累加值,返回最终的累加结果 15。 除了数组的求和,reduce 函数还可以用于其他各种用途,如数组求平均数、最大值、最小值等。此外,reduce 函数还可以与 map、filter、forEach 等函数组合使用,实现更加复杂的数据操作。

当然,以下是一些 reduce 的实际应用案例,帮助你更好地理解它的用法:

计算数组的平均数

  1. const arr = [1, 2, 3, 4, 5];
  2. const average = arr.reduce((accumulator, currentValue, index, array) => {
  3. accumulator += currentValue;
  4. if (index === array.length - 1) {
  5. return accumulator / array.length;
  6. } else {
  7. return accumulator;
  8. }
  9. });
  10. console.log(average); // 3

求数组的最大值

  1. const arr = [1, 2, 3, 4, 5];
  2. const max = arr.reduce((accumulator, currentValue) => Math.max(accumulator, currentValue));
  3. console.log(max); // 5

求数组的最小值

  1. const arr = [1, 2, 3, 4, 5];
  2. const min = arr.reduce((accumulator, currentValue) => Math.min(accumulator, currentValue));
  3. console.log(min); // 1

数组去重

  1. const arr = [1, 2, 3, 3, 4, 4, 5];
  2. const uniqueArr = arr.reduce((accumulator, currentValue) => {
  3. if (!accumulator.includes(currentValue)) {
  4. accumulator.push(currentValue);
  5. }
  6. return accumulator;
  7. }, []);
  8. console.log(uniqueArr); // [1, 2, 3, 4, 5]

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

  1. const arr = [1, 2, 3, 3, 4, 4, 5];
  2. const countMap = arr.reduce((accumulator, currentValue) => {
  3. if (!accumulator[currentValue]) {
  4. accumulator[currentValue] = 1;
  5. } else {
  6. accumulator[currentValue]++;
  7. }
  8. return accumulator;
  9. }, {});
  10. console.log(countMap); // {1: 1, 2: 1, 3: 2, 4: 2, 5: 1}

实现数组分组

  1. const arr = [1, 2, 3, 4, 5];
  2. const result = arr.reduce((accumulator, currentValue) => {
  3. if (currentValue % 2 === 0) {
  4. accumulator.even.push(currentValue);
  5. } else {
  6. accumulator.odd.push(currentValue);
  7. }
  8. return accumulator;
  9. }, { even: [], odd: [] });
  10. console.log(result); // {even: [2, 4], odd: [1, 3, 5]}

计算数组中连续递增数字的长度

  1. const arr = [1, 2, 3, 5, 6, 7, 8, 9];
  2. const result = arr.reduce((accumulator, currentValue, index, array) => {
  3. if (index === 0 || currentValue !== array[index - 1] + 1) {
  4. accumulator.push([currentValue]);
  5. } else {
  6. accumulator[accumulator.length - 1].push(currentValue);
  7. }
  8. return accumulator;
  9. }, []);
  10. const maxLength = result.reduce((accumulator, currentValue) => Math.max(accumulator, currentValue.length), 0);
  11. console.log(maxLength); // 5

计算对象数组的属性总和

  1. const arr = [
  2. { name: 'Alice', age: 25 },
  3. { name: 'Bob', age: 30 },
  4. { name: 'Charlie', age: 35 },
  5. ];
  6. const result = arr.reduce((accumulator, currentValue) => accumulator + currentValue.age, 0);
  7. console.log(result); // 90

将对象数组转换为键值对对象

  1. const arr = [
  2. { name: 'Alice', age: 25 },
  3. { name: 'Bob', age: 30 },
  4. { name: 'Charlie', age: 35 },
  5. ];
  6. const result = arr.reduce((accumulator, currentValue) => {
  7. accumulator[currentValue.name] = currentValue.age;
  8. return accumulator;
  9. }, {});
  10. console.log(result); // {Alice: 25, Bob: 30, Charlie: 35}

计算数组中出现次数最多的元素

  1. const arr = [1, 2, 3, 4, 4, 4, 5, 5, 6, 6, 6, 6];
  2. const result = arr.reduce((accumulator, currentValue) => {
  3. accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;
  4. return accumulator;
  5. }, {});
  6. const maxCount = Math.max(...Object.values(result));
  7. const mostFrequent = Object.keys(result).filter(key => result[key] === maxCount).map(Number);
  8. console.log(mostFrequent); // [6]

实现 Promise 串行执行

  1. const promise1 = () => Promise.resolve('one');
  2. const promise2 = (input) => Promise.resolve(input + ' two');
  3. const promise3 = (input) => Promise.resolve(input + ' three');
  4. const promises = [promise1, promise2, promise3];
  5. const result = promises.reduce((accumulator, currentValue) => {
  6. return accumulator.then(currentValue);
  7. }, Promise.resolve('start'));
  8. result.then(console.log); // 'one two three'

对象属性值求和

  1. const obj = {
  2. a: 1,
  3. b: 2,
  4. c: 3
  5. };
  6. const result = Object.values(obj).reduce((accumulator, currentValue) => accumulator + currentValue);
  7. console.log(result); // 6

按属性对数组分组

  1. const arr = [
  2. { id: 1, name: 'John' },
  3. { id: 2, name: 'Mary' },
  4. { id: 3, name: 'Bob' },
  5. { id: 4, name: 'Mary' }
  6. ];
  7. const result = arr.reduce((accumulator, currentValue) => {
  8. const key = currentValue.name;
  9. if (!accumulator[key]) {
  10. accumulator[key] = [];
  11. }
  12. accumulator[key].push(currentValue);
  13. return accumulator;
  14. }, {});
  15. console.log(result);
  16. /*
  17. {
  18. John: [{ id: 1, name: 'John' }],
  19. Mary: [
  20. { id: 2, name: 'Mary' },
  21. { id: 4, name: 'Mary' }
  22. ],
  23. Bob: [{ id: 3, name: 'Bob' }]
  24. }
  25. */

扁平化数组

  1. // 如果你有一个嵌套的数组,可以使用reduce将其扁平化成一个一维数组。例如:
  2. const nestedArray = [[1, 2], [3, 4], [5, 6]];
  3. const flattenedArray = nestedArray.reduce((acc, curr) => acc.concat(curr), []);
  4. console.log(flattenedArray); // [1, 2, 3, 4, 5, 6]

合并对象

  1. // 可以使用reduce将多个对象合并成一个对象。例如:
  2. const obj1 = { a: 1, b: 2 };
  3. const obj2 = { c: 3, d: 4 };
  4. const obj3 = { e: 5, f: 6 };
  5. const mergedObj = [obj1, obj2, obj3].reduce((acc, curr) => Object.assign(acc, curr), {});
  6. console.log(mergedObj); // {a: 1, b: 2, c: 3, d: 4, e: 5, f: 6}

以上就是JavaScript数组对象高阶函数reduce的妙用详解的详细内容,更多关于JavaScript数组对象reduce的资料请关注w3xue其它相关文章!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号