filter map案例

wen java案例 1

本文目录导读:

filter map案例

  1. 基础用法
  2. 高级应用
  3. 实际业务场景
  4. 性能优化技巧
  5. 实用小技巧

我来给你展示几个实用的 filtermap 组合案例。

基础用法

案例1:筛选并转换用户数据

const users = [
  { name: '小明', age: 18, isActive: true },
  { name: '小红', age: 25, isActive: false },
  { name: '小刚', age: 30, isActive: true },
  { name: '小丽', age: 22, isActive: true }
];
// 筛选活跃用户,并只返回他们的名字和年龄
const activeUsers = users
  .filter(user => user.isActive)
  .map(user => `${user.name}(${user.age}岁)`);
console.log(activeUsers); // ['小明(18岁)', '小刚(30岁)', '小丽(22岁)']

案例2:商品价格处理

const products = [
  { name: '手机', price: 5999, inStock: true },
  { name: '电脑', price: 8999, inStock: false },
  { name: '耳机', price: 999, inStock: true },
  { name: '键盘', price: 399, inStock: true },
  { name: '平板', price: 3999, inStock: false }
];
// 筛选有货且价格低于5000的商品,然后添加折扣价
const discountedProducts = products
  .filter(p => p.inStock && p.price < 5000)
  .map(p => ({
    name: p.name,
    originalPrice: p.price,
    discountPrice: p.price * 0.9,  // 9折
    save: p.price * 0.1
  }));
console.log(discountedProducts);
// [{name: '耳机', originalPrice: 999, discountPrice: 899.1, save: 99.9}, ...]

高级应用

案例3:对象数组的复杂筛选

const students = [
  { id: 1, name: '张三', scores: { math: 95, english: 82, chinese: 88 } },
  { id: 2, name: '李四', scores: { math: 72, english: 90, chinese: 65 } },
  { id: 3, name: '王五', scores: { math: 88, english: 75, chinese: 92 } },
  { id: 4, name: '赵六', scores: { math: 60, english: 70, chinese: 55 } }
];
// 找出所有科目都及格的学生,并计算他们的平均分
const passingStudents = students
  .filter(student => 
    Object.values(student.scores).every(score => score >= 60)
  )
  .map(student => ({
    name: student.name,
    average: (Object.values(student.scores).reduce((a, b) => a + b, 0) / 3).toFixed(1),
    isGood: student.scores.math >= 85 && student.scores.chinese >= 85
  }));
console.log(passingStudents);

案例4:字符串数组处理

const emails = ['john@gmail.com', 'invalid-email', 'jane@yahoo.com', 'test@', 'bob@hotmail.com'];
// 过滤无效邮箱,并提取域名
const validDomains = emails
  .filter(email => email.includes('@') && email.split('@')[1].includes('.'))
  .map(email => email.split('@')[1]);
console.log(validDomains); // ['gmail.com', 'yahoo.com', 'hotmail.com']

实际业务场景

案例5:订单处理系统

const orders = [
  { id: 'A001', items: ['手机', '壳'], total: 6200, status: 'completed' },
  { id: 'A002', items: ['电脑'], total: 8999, status: 'pending' },
  { id: 'A003', items: ['耳机', '键盘', '鼠标'], total: 1500, status: 'completed' },
  { id: 'A004', items: ['显示器'], total: 2500, status: 'cancelled' },
  { id: 'A005', items: ['键盘', '键盘', '键盘'], total: 1200, status: 'completed' }
];
// 获取已完成订单的汇总信息
const completedOrderSummary = orders
  .filter(order => order.status === 'completed')
  .map(order => ({
    orderId: order.id,
    itemCount: order.items.length,
    uniqueItems: new Set(order.items).size,
    total: `¥${order.total}`,
    isBigOrder: order.total > 5000
  }));
console.log(completedOrderSummary);

案例6:数据处理管道

// 从API获取的数据
const rawData = [
  { name: '项目A', budget: 100000, spent: 45000, risk: 'high' },
  { name: '项目B', budget: 50000, spent: 55000, risk: 'low' },
  { name: '项目C', budget: 200000, spent: 80000, risk: 'medium' },
  { name: '项目D', budget: 30000, spent: 15000, risk: 'low' }
];
// 找出有风险的项目(超支或高风险),并格式化数据
const riskyProjects = rawData
  .filter(project => 
    project.risk === 'high' || 
    project.spent > project.budget * 0.7  // 花费超预算70%
  )
  .map(project => ({
    projectName: project.name.toUpperCase(),
    budgetUtilization: `${Math.round((project.spent / project.budget) * 100)}%`,
    status: project.spent > project.budget ? '超支' : '在预算内',
    alert: project.spent > project.budget ? '⚠️' : ''
  }));
console.log(riskyProjects);

性能优化技巧

// 方法1:使用链式调用(可读性好,但会遍历两次)
const result1 = array.filter(fn1).map(fn2);
// 方法2:使用 reduce 代替(只遍历一次)
const result2 = array.reduce((acc, item) => {
  if (fn1(item)) {
    acc.push(fn2(item));
  }
  return acc;
}, []);
// 方法3:使用 flatMap
const result3 = array.flatMap(item => 
  fn1(item) ? [fn2(item)] : []
);

实用小技巧

// 转为数字数组并过滤NaN
const mixed = ['1', '2', '3', 'abc', '4', 'def'];
const numbers = mixed
  .map(Number)
  .filter(n => !isNaN(n));
// [1, 2, 3, 4]
// 去重
const duplicate = [1, 2, 2, 3, 3, 4, 5, 5];
const unique = duplicate
  .filter((value, index, self) => self.indexOf(value) === index);
// [1, 2, 3, 4, 5]
// 或者使用更简洁的方式
const unique2 = [...new Set(duplicate)];

这些案例展示了 filtermap 组合使用的强大功能,可以根据实际需求灵活组合,希望这些例子对你有帮助!

上一篇collect案例

下一篇Predicate案例

抱歉,评论功能暂时关闭!