-1

I have a JSON URL (https://api.rawg.io/api/games?page=3), and I'm trying to make a appear the name, picture, the slug and the platforms on my front page. I have a idea like sort the most played games and push there id's in a array. But I don't know how I can first sort their number of players and then conserve their id's in an array.

code:

let array = ['']

function sort(x){
    var swapped = true;
    while(swapped){
        swapped = false;
        for (let i = 0; i<x.length;i++){
            if (x[i] > x[i+1]){
                let newnmb = x[i+1];
                x[i+1] = x[i];
                x[i] = newnmb;
                swapped = true;
            }
        }
    }
}

for(page=1;page<=15;page++){
    fetch('https://api.rawg.io/api/games?page='+page)
    .then(response => {
      return response.json()
    })
    .then(data => {
        let i = 0
        while(data.results[i]){ 
            if(typeof data.results[i].added_by_status.playing == 'undefined'){
            }
            else{
                array.push(data.results[i].added_by_status.playing);
            }
            i++
          }
          sort(array)
    })
}

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Gobii
  • 21
  • 5
  • could you show us an example of the array you're trying to sort? – torquan Apr 03 '20 at 13:39
  • @torquan Just modified my code – Gobii Apr 03 '20 at 13:45
  • Example data are needed. – Reporter Apr 03 '20 at 13:47
  • You don't need to write your own sort function. You likely get back an object (?) You should transform this in an array and than sort that array with array.sort(comparator). Your comparator would compare the players number, – torquan Apr 03 '20 at 13:49
  • @Reporter You mean from the json url ? – Gobii Apr 03 '20 at 13:49
  • @torquan my function seems to works but if its better i'll change it – Gobii Apr 03 '20 at 13:50
  • The array you want to sort it. – Reporter Apr 03 '20 at 14:01
  • Please provide a small representation of the data from that URL. Stack Overflow questions should be self-contained, not reliant on external data or code to be answered. Generally we want a [mre] for these kinds of questions. You can likely use [Stack Snippets](https://meta.stackoverflow.com/q/358992/215552) to make it. – Heretic Monkey Apr 03 '20 at 14:42

2 Answers2

0

Your code would look like this:

// your result from the API
const resultObject = {};
let resultArray = [];
// transform JSON object to an array
Object.keys(resultObject).forEach((key, index) => {
  resultArray.push(resultObject[key]);
});

// comparator
function sortByPlayerCount(firstEl, secondEl) {
  return firstEl.added_by_status.playing - secondEl.added_by_status.playing;
}

// sort array by player count
resultArray.sort(sortByPlayerCount);
torquan
  • 356
  • 1
  • 6
0

You should wait until all the pages are received, use async / await and wait for the result with then().

For sorting on playcount, use array.sort().

Small example, please see comments in the code

async function getGames(max = 10) {

    // Temporary hold games
    let games = [];

    // For number of pages
    for(let page=1;page<=max;page++) {

        // Get API response
        await fetch('https://api.rawg.io/api/games?page=' + page).then((response) => response.json()).then((data) => {

            // For each game in the response
            data.results.forEach((value) => {

                // Push to tmp array
                games.push(value);
            })
        });
    }

    // Return games
    return games;
}

// Get and wait allGames
getGames().then((allGames) => {

    // Sort games on playtime
    allGames.sort((a,b) => (a.playtime < b.playtime) ? 1 : ((b.playtime < a.playtime) ? -1 : 0));

    // Loop through best 10 games
    for(let toShow=0;toShow<=20;toShow++) {
    
        // Get game by for index
        const tmpGame = allGames[toShow];
        
        // Write some info to docuemnt
       document.write(tmpGame.name + '---' + tmpGame.playtime + '<br>');
    }
});
0stone0
  • 34,288
  • 4
  • 39
  • 64