Friend, I did some major changes to your function and now it works just fine.
const fetchData = async ( url ) => await (await fetch(url)).json();
const getPlayerData = async () =>
{
// Gets all enumerable values directly as an array.
const players = Object.values
(
await fetchData("https://api.sleeper.app/v1/players/nfl")
);
const rankedPlayers = players
.filter
(
// Filters if a player is active and has a rank (not undefined or null).
player => ( player.active && (player.search_rank != null) )
)
.sort
(
// Sorts the players by `search_rank` only.
( a, b ) => a.search_rank - b.search_rank
);
return rankedPlayers;
}
console.clear();
console.log('Fetching data...');
getPlayerData().then
(
rankedPlayers => console.log
({
'Number of ranked players': rankedPlayers.length,
'First in the list':
{
'Parsed full name': rankedPlayers.at(0).first_name + ' ' + rankedPlayers.at(0).last_name,
'Search rank': rankedPlayers.at(0).search_rank,
},
'Second in the list':
{
'Parsed full name': rankedPlayers.at(1).first_name + ' ' + rankedPlayers.at(1).last_name,
'Search rank': rankedPlayers.at(1).search_rank,
},
'Third in the list':
{
'Parsed full name': rankedPlayers.at(2).first_name + ' ' + rankedPlayers.at(2).last_name,
'Search rank': rankedPlayers.at(2).search_rank,
},
})
);
.as-console-wrapper { min-height: 100%; }
PS.: I noticed that the data contains non-unique search_rank
values. So, it maybe is better to change the .sort()
callback function to fit all criteria for the desired sorting... Like, if there's two search_rank
with the same value, which should be sorted first then? In the current example they'll stay in place (so, the first as sorted in the raw data comes first).
By the way, it's possible to make it a one-liner:
// One-liner:
const getPlayerData = async () => Object.values(await (await fetch("https://api.sleeper.app/v1/players/nfl")).json()).filter(player => ( player.active && (player.search_rank != null) )).sort(( a, b ) => a.search_rank - b.search_rank);
// TEST:
console.clear();
console.log('Fetching data...');
getPlayerData().then
(
rankedPlayers => console.log
({
'Ranked Players': rankedPlayers.length,
'First Player': rankedPlayers.at(0),
})
);
const players = Object.values(allPlayers)
would be way better than what you did there... Then you just need toconst activePlayers = players.filter(player => player.active && (player.search_rank !== null))
. Then you can populate another variable likeconst rankedActivePlayers = activePlayers.sort(...)
. Also, I think your.sort(...)
callback should be different, like(a, b) => a.search_rank == b.search_rank ? 0 : a.search_rank > b.search_rank ? 1 : -1
. This way, ifa.search_rank
is greater thanb.search_rank
thenb
will come first.