I need to filter out objects in array if specific key value is null.(trying to learn)
const getPlayerData = async () => {
const allPlayers = await fetchData("https://api.sleeper.app/v1/players/nfl");
const players = Object.keys(allPlayers).map(function(key) {
return allPlayers[key]
})
const activePlayers = await Promise.all(players?.filter(async(player: any) => {player.search_rank !== null}
).sort((a, b) => a.search_rank - b.search_rank));
console.log(activePlayers)
return activePlayers;
}
it filters if {player.active = true}
but i need to filter if player.search_rank
is null
aswell
I've modified the above code assuming that fetchData
function will get the data from API. Please ignore the implementation of fetchData.
const fetchData = async (url) => {
return await fetch(url).then(res => res.json())
}
const getPlayerData = async () => {
const allPlayers = await fetchData("https://api.sleeper.app/v1/players/nfl");
const players = Object.keys(allPlayers).map((key) => allPlayers[key]);
const activePlayers = players
?.filter((player) => player.search_rank !== null)
.sort((a, b) => a.search_rank - b.search_rank);
console.log(activePlayers)
return activePlayers;
}
Changes made:
const players
to use arrow function and return it without explicitly writing return statement. --- You may ignore this change.Promise.all
as the data is already received and we are applying filter and sort functions which are synchronous operations. async
is also not required inside the filter
callback as we are not performing any asynchronous operations inside filter
function.The main issue is we have to return player.search_rank !== null
which is present inside filter function or write it as arrow function without brackets {}
.