I wanna sort this array in ascending order based on the max ranking in the objects, but there are certain objects that have null values for ranking , I want to throw the objects with null at the end, here is what I tried but it’s not working , when I am logging the first 10 ranks of the sorted array I still have undefined values
async function getLive(){
let response= await fetch('https://tennisapi1.p.rapidapi.com/api/tennis/events/live', options)
let json= await response.json()
for(let i=0; i<10;i++){
console.log(json.events[i].awayTeam.ranking<json.events[i].homeTeam.ranking?json.events[i].awayTeam.ranking:json.events[i].homeTeam.ranking)
}
json.events.sort((a, b) => {
let x=1000000
let r1 = Math.min(a.awayTeam.ranking , a.homeTeam.ranking)
if(r1===null){
r1=x
}
x+=1
let r2 = b.awayTeam.ranking < b.homeTeam.ranking ? b.awayTeam.ranking : b.homeTeam.ranking;
if(r2===null){
r2=x
}
x++
return r1 - r2;
});
live=json.events
console.log('-----------------------------')
for(let i=0; i<10;i++){
console.log(Math.min(live[i].awayTeam.ranking ,live[i].homeTeam.ranking))
}
when I log here is what I get, why are the Nan values there it makes no sense
121
NaN
NaN
73
192
295
360
394
473
475
3
Answers
I don’t know what your data looks like, but here is an example with a simple array:
There is a neat trick to make this simple. You can just coalesce
null
values as-Infinity
!This way, any
null
(orundefined
) value will be replaced by the smallest possible value, hence it goes to the very end of the array.An alternative solution would be to first partition the array into "rated" and "unrated" items based on whether
rating
isnull
, then sort the rated items, and finally concatenating the two using the spread operator: