0

I am fetching data from a JSON file and rendering it to a table, but I need to sort it by ratings and votes with select options I've tried different ways but none of them worked.

This is a link to my code: https://jsfiddle.net/natefr0st/596ew8zc/5/

I've tried to get the ratings with querySelectorAll and loop through each rating and then sort it but it didn't work, tried other different methods and again without result

const sortMenu = document.getElementById('sort');
sortMenu.addEventListener('change', sortTable);

function sortTable() {
    const rating = document.querySelectorAll('.rating')
    // rating.forEach((val, i) => console.log(val.innerHTML));

    // function compare(a, b) {
    //  return a.imdb_rating > b.imdb_rating ? 1 : -1;
    // }    

    if(sortMenu.value == 1) {
        rating.forEach(function(val, index) {
            let ratingArr = Array.from(val.innerHTML);
            return ratingArr.sort();
        });
    } 
}

2 Answers 2

1

Use below code base. FYI, I have tested it in your fiddle.

    let movies = [];
    const url = 'url';

   $.getJSON(url, (data) => {
        start(data, true)
    });

   function start(data, init=false) {
      movies = data
      displayMovies();
      if (init) {
          setPages();
      }
   }

    // Render 10 Rows Per Page
    // ========================
    function displayMovies(page = 1) {
        let movie_data = '';
        let max = page * 10;
        let min = max - 10;

        for (let i = min; i < max; i++) {
            let movie = movies[i];
            if (movie) {
                movie_data += `<tr class="movie-row">
                        <td scope="row">${movie.id}</td>
                        <td>${movie.title}</td>
                        <td>${movie.director}</td>
                        <td>${movie.distributor}</td>
                        <td class="rating">${movie.imdb_rating}</td>
                        <td class="votes">${movie.imdb_votes}</td>
                        <td><button type="button" class="btn btn-danger">Delete</button></td>
                    </tr>`;
            } else {
                break;
            }
        }

        $('#movies').html(movie_data);
    }

    // Render Pagination Buttons to the Table
    // =======================================
    function setPages() {
        let nbPages = Math.ceil(movies.length / 10);
        let pages = '';
        for (let i = 1; i <= nbPages; i++) {
            pages +=
                '<button class="btn btn-outline-info page-btn" type="button" page="' + i + '">Page ' + i + '</button>';
        }
        $('#pages').append(pages);
        $('.page-btn').click(function () {
            displayMovies($(this).attr('page'));
        });
    }

  // Sort Table TODO
    // ================
    const sortMenu = document.getElementById('sort');
    sortMenu.addEventListener('change', sortTable);

    function sortTable() {
        switch(parseInt(sortMenu.value)) {
            case 1:
                movies.sort((a, b) => (a.imdb_votes - b.imdb_votes));
                start(movies);
                break;
            case 2:
                movies.sort((a, b) => (b.imdb_votes - a.imdb_votes));
                start(movies);
                break;
            case 3: 
                movies.sort((a, b) => (a.imdb_rating - b.imdb_rating));
                start(movies);
                break;
            case 4:
                movies.sort((a, b) => (b.imdb_rating - a.imdb_rating));
                start(movies);
                break;
            default:
                break;
        }
    }
Sign up to request clarification or add additional context in comments.

10 Comments

Oh but now renders the buttons for the pagination onchange many times :/
Done. please check.
FYI, I have added init flag in start function.
Thanks a lot but can you explain it plz :}
Yes. Best way to sort it in your case is to sort array before init table. And when init table, setPages function is called only one time with status value of init flag.
|
0

Why dont you make your life easy by just using below.

Let jquery datatable plugin generate html for you you are creating your self, if below link fulfill your requirements this is best way.

https://datatables.net/examples/data_sources/js_array.html

2 Comments

I am not allowed to use such tools
Ok in this case you have to add a row above TH of your columns with drop-down having on change click..on selected item change just call api again with order by selected value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.