js计算排名

1.假数组:

studentList:[{
    name:'张三',
    store:99,
    ranking:1,
},{
    name:'李四',
    store:98,
    ranking:2,
},{
    name:'王五',
    store:98,
    ranking:3,
},{
    name:'赵四',
    store:96,
    ranking:4,
},{
    name:'张好',
    store:96,
    ranking:5,
},{
    name:'李丽',
    store:95,
    ranking:6,
},{
    name:'王强',
    store:95,
    ranking:7,
}]

2、计算排名:

(1)分数相同,排名并列,按排名12345升序排列

let prescore = 0;//预定义分数
let ranking = 0;//排名
 
studentList.forEach((item,index)=>{
    if(item.store==prescore){
        item.ranking = ranking;
    }else{
        ranking++;
        prescore = item.store;
        item.ranking = ranking;
    }
})
console.log(studentList)

效果图:

js计算排名_第1张图片

(2)分数相同,排名并列,按人数排名

let prescore = 0;//预定义分数
let ranking = 0;//排名
let same = 0; //是否相同
 
studentList.forEach((item,index)=>{
    if(item.store==prescore){
        item.ranking = ranking;
        same++;
    }else{
	ranking = ranking + same;
        ranking++;
        prescore = item.store;
        same=0;
        item.ranking = ranking;
    }
})

效果图:

js计算排名_第2张图片

 

转载于:https://zhuanlan.zhihu.com/p/128474165

 

 

 

 

 

 

你可能感兴趣的:(js)