对以下数据 取出每人(name)最大的销售量(sales)数据 ( 对sales排序对name去重) var arr = [ { name: "小明", year: 2019, sales: 53 }, { name: "小明", year: 2020, sales: 234 }, { name: "小明", year: 2018, sales: 24 }, { name: "小强", year: 2019, sales: 31 }, { name: "小强", year: 2020, sales: 567 }, { name: "小强", year: 2018, sales: 678 }, { name: "小红", year: 2019, sales: 465 }, { name: "小红", year: 2020, sales: 82 }, { name: "小红", year: 2018, sales: 576 }, { name: "小马", year: 2019, sales: 4567 }, { name: "小马", year: 2020, sales: 832 }, { name: "小马", year: 2018, sales: 674 }, ];
时间: 2024-04-15 20:25:21 浏览: 71
你可以使用以下代码来取出每个人的最大销售量数据,并按照销售量进行排序,并去除重复的姓名:
```javascript
var arr = [
{ name: "小明", year: 2019, sales: 53 },
{ name: "小明", year: 2020, sales: 234 },
{ name: "小明", year: 2018, sales: 24 },
{ name: "小强", year: 2019, sales: 31 },
{ name: "小强", year: 2020, sales: 567 },
{ name: "小强", year: 2018, sales: 678 },
{ name: "小红", year: 2019, sales: 465 },
{ name: "小红", year: 2020, sales: 82 },
{ name: "小红", year: 2018, sales: 576 },
{ name: "小马", year: 2019, sales: 4567 },
{ name: "小马", year: 2020, sales: 832 },
{ name: "小马", year: 2018, sales: 674 },
];
// 根据销售量进行排序
arr.sort(function(a, b) {
return b.sales - a.sales;
});
var result = {};
arr.forEach(function(item) {
// 判断是否已存在最大销售量数据
if (!result[item.name]) {
result[item.name] = item;
}
});
// 获取最大销售量数据数组
var output = Object.values(result);
console.log(output);
```
运行以上代码,你将得到以下结果:
```javascript
[
{ name: "小马", year: 2019, sales: 4567 },
{ name: "小强", year: 2018, sales: 678 },
{ name: "小红", year: 2018, sales: 576 },
{ name: "小明", year: 2020, sales: 234 }
]
```
这个结果是根据销售量从大到小排序的,且每个人只保留了其最大销售量的数据,并且去除了重复的姓名。
阅读全文