javascript在项目中常用的算法(一)

1.筛选:使用filter方法对数组进行筛选,可以根据条件返回符合条件的对象数组。例如,对于一个包含学生信息的对象数组,可以使用以下代码筛选出成绩大于等于90分的学生:

const students = [
  { name: 'Alice', score: 85 },
  { name: 'Bob', score: 92 },
  { name: 'Charlie', score: 88 },
  { name: 'David', score: 96 },
];

const topStudents = students.filter(student => student.score >= 90);

2.排序:使用sort方法对数组进行排序,可以根据指定的属性进行升序或降序排序。例如,对于上面的学生信息对象数组,可以使用以下代码按照成绩降序排序:

const sortedStudents = students.sort((a, b) => b.score - a.score);

3.分组:使用reduce方法对数组进行分组,可以根据指定的属性将对象数组分组。例如,对于一个包含商品信息的对象数组,可以使用以下代码将商品按照类别分组:

const products = [
  { name: 'Apple', category: 'Fruit' },
  { name: 'Banana', category: 'Fruit' },
  { name: 'Carrot', category: 'Vegetable' },
  { name: 'Tomato', category: 'Vegetable' },
];

const groupedProducts = products.reduce((groups, product) => {
  const key = product.category;
  if (!groups[key]) {
    groups[key] = [];
  }
  groups[key].push(product);
  return groups;
}, {});

4.映射:使用map方法对数组进行映射,可以根据指定的属性返回新的对象数组。例如,对于上面的学生信息对象数组,可以使用以下代码将学生的成绩转换为字母等级

const letterGrades = {
  90: 'A',
  80: 'B',
  70: 'C',
  60: 'D',
  0: 'F',
};

const gradedStudents = students.map(student => ({
  name: student.name,
  grade: letterGrades[Math.floor(student.score / 10) * 10],
}));

5.去重:使用reduce方法对数组进行去重,可以根据指定的属性将重复的对象去除。例如,对于一个包含重复商品信息的对象数组,可以使用以下代码去除重复的商品:

const products = [
  { name: 'Apple', category: 'Fruit' },
  { name: 'Banana', category: 'Fruit' },
  { name: 'Carrot', category: 'Vegetable' },
  { name: 'Tomato', category: 'Vegetable' },
  { name: 'Apple', category: 'Fruit' },
];

const uniqueProducts = products.reduce((unique, product) => {
  const key = product.name + product.category;
  if (!unique[key]) {
    unique[key] = product;
  }
  return unique;
}, {});

const result = Object.values(uniqueProducts);

6.嵌套:使用map方法对数组进行嵌套,可以根据指定的属性将对象数组嵌套为多层结构。例如,对于一个包含分类和商品信息的对象数组,可以使用以下代码将商品按照类别嵌套:

const products = [
  { name: 'Apple', category: 'Fruit' },
  { name: 'Banana', category: 'Fruit' },
  { name: 'Carrot', category: 'Vegetable' },
  { name: 'Tomato', category: 'Vegetable' },
];

const categories = [...new Set(products.map(product => product.category))];

const nestedProducts = categories.map(category => ({
  name: category,
  products: products.filter(product => product.category === category),
}));

7.扁平化:使用reduce方法对数组进行扁平化,可以将多维数组转换为一维数组。例如,对于以下多维数组,可以使用以下代码将其扁平化:

const arr = [[1, 2], [3], [4, 5, 6]];
const flatArr = arr.reduce((flat, subArr) => flat.concat(subArr), []);

8.按照属性分组:假设有一个包含订单信息的对象数组,每个对象包含订单号、商品名称和商品数量。现在需要将这个对象数组按照订单号分组,每个组包含这个订单下的所有商品信息。可以使用 reduce 方法实现:

const orders = [
  { orderId: 1, name: 'apple', quantity: 2 },
  { orderId: 1, name: 'banana', quantity: 3 },
  { orderId: 2, name: 'orange', quantity: 4 },
  { orderId: 2, name: 'pear', quantity: 5 },
];

const groupedOrders = orders.reduce((groups, order) => {
  const key = order.orderId;
  if (!groups[key]) {
    groups[key] = [];
  }
  groups[key].push({ name: order.name, quantity: order.quantity });
  return groups;
}, {});

const result = Object.values(groupedOrders);

9.对象数组根据某个属性值进行分组

let arr = [
  {id: 1, name: 'Tom', age: 18},
  {id: 2, name: 'Jack', age: 20},
  {id: 3, name: 'Lucy', age: 22},
  {id: 4, name: 'Jerry', age: 18},
  {id: 5, name: 'Rose', age: 20},
  {id: 6, name: 'Bob', age: 22}
];

let group = arr.reduce(function(acc, cur) {
  if (acc[cur.age]) {
    acc[cur.age].push(cur);
  } else {
    acc[cur.age] = [cur];
  }
  return acc;
}, {});

console.log(group);

10.拓展 使用js和moment.js实现今年明年后年的每个月的第一天

// 引入moment.js库
const moment = require('moment');

// 获取当前时间
let now = moment();

// 构造三个日期对象,分别为今年、明年、后年的1月1日
let thisYear = moment().startOf('year');
let nextYear = moment().add(1, 'year').startOf('year');
let yearAfterNext = moment().add(2, 'year').startOf('year');

// 分别生成3年内每月的第一天日期对象
let dates = [];
for (let year of [thisYear, nextYear, yearAfterNext]) {
  for (let month = 0; month < 12; month++) {
    let date = moment(year).add(month, 'month').startOf('month');
    dates.push(date);
  }
}

// 输出所有日期
for (let date of dates) {
  console.log(date.format('YYYY-MM-DD'));
}

11.拓展 遍历对象数组,生成二维对象数组,例子比如echarts折线图标域的实现

const colors = [
  'rgba(255, 133, 147, 0.4)',
  'rgba(255, 136, 187, 0.4)',
  'rgba(255, 188, 131, 0.4)',
  'rgba(255, 133, 121, 0.4)',
]
const list =[{},{},{}];

function convert(list, colors) {
  return list.map((item, index) => {
    const { trendname, ...ele } = item
    return Object.values(ele).map(val => ({
      name: trendname,
      xAxis: val,
      itemStyle: {
        color: colors[index]
      },
    }))
  })
}

12.拓展遍历对象数组,过滤掉值中有null , '',undefined的键值对

let arr = [
  {name: 'Alice', age: 20, sex:'man'},
  {name: 'Bob', age: null, gender: 'male'},
  {name: 'Charlie', age: '', hobby: 'swimming'},
  {name: 'David', age: undefined, occupation: 'engineer'},
];

newArr = arr.map(obj => {
  return Object.fromEntries(
    Object.entries(obj).filter(([key, val]) => {
      return val !== null && val !== '' && val !== undefined;
    })
  );
});

console.log(newArr);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值