前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >根据规则过滤掉数组中的重复数据

根据规则过滤掉数组中的重复数据

作者头像
德顺
发布2024-03-29 12:38:53
940
发布2024-03-29 12:38:53
举报
文章被收录于专栏:前端资源前端资源

今天有一个需求,有一些学生成绩的数据,里面包含一些重复信息,需要从数组对象中过滤掉重复的数据。

例如,有一个包含学生成绩的数组,其中每个学生的成绩可能出现多次。我们需要从这个数组中过滤掉重复的成绩,只保留每个学生最高的分数。

可以使用 Array.prototype.filter() 方法来过滤掉数组中的重复数据。该方法接受一个回调函数作为参数,判断数组中的每个元素是否满足某个条件。如果回调函数返回 true,则该元素将被保留在新的数组中。否则,该元素将被过滤掉。

以下是过滤掉数组中的重复数据的示例:

代码语言:javascript
复制
const numbers = [1, 2, 3, 4, 5, 1, 2, 3];

const uniqueNumbers = numbers.filter((number, index, arr) => {
  return arr.indexOf(number) === index;
});

console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

这段代码使用 Array.prototype.filter() 方法来过滤数组 numbers 中的重复数据。回调函数 (number, index, arr) => { return arr.indexOf(number) === index; } 检查数组 arr 中每个元素 number 是否只出现一次。如果元素 number 只出现一次,则回调函数返回 true,该元素将被保留在新的数组 uniqueNumbers 中。否则,回调函数返回 false,该元素将被过滤掉。

我们还可以使用 Array.prototype.filter() 方法来根据更复杂的规则过滤掉数组中的重复数据。

例如,我们可以根据对象的某个属性来过滤掉重复的数据。可以参考下面的示例:

代码语言:javascript
复制
const students = [
  { name: "John", score: 90 },
  { name: "Mary", score: 80 },
  { name: "John", score: 95 },
  { name: "Mary", score: 85 },
  { name: "Mary", score: 75 },
];

const uniqueStudents = students.filter((student, index, arr) => {
  return arr.findIndex((s) => s.name === student.name) === index;
});

console.log(uniqueStudents);

// [
//   {
//     name: 'John',
//     score: 90,
//   },
//   {
//     name: 'Mary',
//     score: 80,
//   },
// ];

还可以只针对分数小于等于 80 的进行过滤,大于 80 的直接返回:

代码语言:javascript
复制
const uniqueStudents = students.filter((student, index, arr) => {
  return student.score > 80 || arr.findIndex((s) => s.name === student.name) === index;
});

console.log(uniqueStudents);

// [
//   {
//     name: 'John',
//     score: 90,
//   },
//   {
//     name: 'Mary',
//     score: 80,
//   },
//   {
//     name: 'John',
//     score: 95,
//   },
//   {
//     name: 'Mary',
//     score: 85,
//   },
// ];

以上就是过滤数组中重复数据的一个思路和实现,希望这篇文章对您有所帮助。

未经允许不得转载:Web前端开发资源网 » 根据规则过滤掉数组中的重复数据

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档