当前位置:首页 > JavaScript

reduce实现js

2026-03-13 18:24:49JavaScript

使用 reduce 实现数组求和

reduce 可以对数组元素进行累加求和。初始值设为 0,回调函数将当前值累加到总和。

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 输出: 10

使用 reduce 实现数组扁平化

通过递归或直接拼接子数组,reduce 可将多维数组扁平化为一维数组。

const nestedArray = [1, [2, [3, [4]]]];
const flatten = (arr) => 
  arr.reduce((flat, item) => 
    flat.concat(Array.isArray(item) ? flatten(item) : item), []);
console.log(flatten(nestedArray)); // 输出: [1, 2, 3, 4]

使用 reduce 统计元素出现次数

通过初始化一个空对象,reduce 可以统计数组中各元素的出现频率。

const fruits = ['apple', 'banana', 'apple', 'orange'];
const count = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1;
  return acc;
}, {});
console.log(count); // 输出: {apple: 2, banana: 1, orange: 1}

使用 reduce 实现数组去重

利用 reduceincludes 方法,可以过滤掉重复元素。

const duplicates = [1, 2, 2, 3, 4, 4];
const unique = duplicates.reduce((acc, num) => 
  acc.includes(num) ? acc : [...acc, num], []);
console.log(unique); // 输出: [1, 2, 3, 4]

使用 reduce 实现对象属性分组

根据对象的某个属性值,reduce 可以将对象数组分组为键值对结构。

const people = [
  { name: 'Alice', age: 21 },
  { name: 'Bob', age: 21 },
  { name: 'Charlie', age: 22 }
];
const grouped = people.reduce((groups, person) => {
  const key = person.age;
  groups[key] = groups[key] || [];
  groups[key].push(person);
  return groups;
}, {});
console.log(grouped);
// 输出: {21: [{name: 'Alice', age: 21}, {name: 'Bob', age: 21}], 22: [{name: 'Charlie', age: 22}]}

使用 reduce 实现管道函数组合

通过 reduce 可以将多个函数依次组合,形成管道式调用。

reduce实现js

const pipe = (...fns) => (x) => fns.reduce((v, fn) => fn(v), x);
const add1 = x => x + 1;
const double = x => x * 2;
const process = pipe(add1, double);
console.log(process(3)); // 输出: 8 (3 + 1 = 4, 4 * 2 = 8)

标签: reducejs
分享给朋友:

相关文章

js实现

js实现

实现 JavaScript 功能的方法 在 JavaScript 中实现特定功能通常涉及多个步骤。以下是常见的实现方法: 基础语法和变量声明 使用 let 或 const 声明变量: let co…

js实现选项卡

js实现选项卡

实现选项卡的基本思路 选项卡通常由一组标签和对应的内容面板组成。点击标签时,显示对应的内容面板,隐藏其他面板。实现这一效果需要结合HTML结构、CSS样式和JavaScript交互逻辑。 HTML结…

js实现验证

js实现验证

验证表单输入 使用JavaScript验证表单输入是常见的需求。可以通过监听表单提交事件,检查输入字段是否符合要求。 document.getElementById('myForm').addEve…

js实现论坛

js实现论坛

实现论坛的基本功能 使用JavaScript实现一个论坛需要结合前端和后端技术。前端可以使用React、Vue或Angular等框架,后端可以选择Node.js配合Express或Koa框架。数据库可…

js实现防洪

js实现防洪

防抖(Debounce)实现 防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。 function debounce(func,…

js实现游标

js实现游标

使用JavaScript实现游标 在JavaScript中,可以通过操作DOM元素的cursor样式属性来实现自定义游标效果。以下是几种常见的实现方法: 修改默认鼠标指针样式 通过CSS的curso…