比较对象里面字段的数字大小,取得最高的4个

[
{count:0,name:'1'},
{count:0,name:'2'},
{count:0,name:'3'},
{count:0,name:'4'},
...
]

5 个回答

``````/**
* 每次点击之后就调用这个函数进行更新
* @param num
*/
const getTopFourCount = (num: IProps[]):number[] => {
// res的顺序从大到小
let res:number[] = [];
num.forEach((item, index) => {
// 目标是top4，所以最少4个才排序
if(res.length >= 4 && item.count > res[3]) {
res.pop();
}
if(res.length < 4) {
res.push(item.count);
res = res.sort((a, b) => b - a);
}
})
return res;
}``````

https://codesandbox.io/s/aged...:260-647

• 2.6k
``````var data = Array(10).fill(0).map((_,i) => ({count: 0, name: i+1}));
var maxs = []; // 存储前4个最大值，按从大到小排序
var indexes = []; // 存储最大值对应的源数据中的索引

function incCount(data, index) {
update(++data[index].count, index);
}

function update(count, index) {
const i = indexes.indexOf(index);

if(i==-1) {
if(maxs.length<4) {
maxs.push(count);
indexes.push(index);
} else {
sort(maxs.length-1, count, index)
}
} else {
sort(i, count, index)
}
}
function sort(i, count, index) {
while(i>=0) {
if(i == 0 || maxs[i-1] >= count) {
maxs[i] = count;
indexes[i] = index;
break;
}
maxs[i] = maxs[i-1];
indexes[i] = indexes[i-1];
i--;
}
}

// inc
incCount(data, 0)

incCount(data, 0)

incCount(data, 0)

incCount(data, 1)

incCount(data, 2)

incCount(data, 3)

incCount(data, 3)``````

• 12.2k