- var list = [{type:1, des:"dddd", votes:80},
- {type:2, des:"dddd", votes:60},
- {type:3, des:"dddd", votes:70},
- {type:1, des:"dddd", votes:50},
- {type:3, des:"dddd", votes:80},
- {type:8, des:"dddd", votes:80},
- {type:9, des:"dddd", votes:20},
- {type:1, des:"dddd", votes:100},
- {type:3, des:"dddd", votes:30}]
读题:首先第一步需要将type等于1的挑选出来,只保留最大的元素,
然后需要将数组以votes从大到小排列
- var list = [
- { type: 1, des: "dddd", votes: 80 },
- { type: 2, des: "dddd", votes: 60 },
- { type: 3, des: "dddd", votes: 70 },
- { type: 1, des: "dddd", votes: 50 },
- { type: 3, des: "dddd", votes: 80 },
- { type: 8, des: "dddd", votes: 80 },
- { type: 9, des: "dddd", votes: 20 },
- { type: 1, des: "dddd", votes: 100 },
- { type: 3, des: "dddd", votes: 30 },
- ];
-
- // 使用 reduce 方法合并相同 type 的元素,并保留 votes 最大的那个
- var result = list.reduce((accumulator, currentItem) => {
- // 查找 accumulator 中是否已经有一个相同 type 的元素
- var existingItem = accumulator.find(
- (item) => item.type === currentItem.type
- );
- // 如果没有找到,或者找到的元素的 votes 比当前元素的 votes 小,则添加或替换当前元素
- if (!existingItem || existingItem.votes < currentItem.votes) {
- if (!existingItem) {
- accumulator.push(currentItem);
- } else {
- existingItem.votes = currentItem.votes;
- // 如果你想完全替换 existingItem,你可以这样做:
- // accumulator[accumulator.indexOf(existingItem)] = currentItem;
- }
- }
- return accumulator;
- }, []);
-
- // 使用 sort 方法对结果按照 votes 从大到小排序
- result.sort((a, b) => b.votes - a.votes);
- console.log(result);
点个赞啦!