2

I am just using Jquery to create a list of my products in my html document from the json data. I was just trying to be able to sort my products through clicking my heading name which will sort my products by alphabetical order.

I have researched on how to do this but cant find/understand how i can do this through using my data from json.

Any help is appreciated. Thanks

function drawPage() {
    $.get('/products', function (data) {
        console.log(data);
        var prod = data.products;

        for(var i=0; i<prod.length; i++){
        var el = document.createElement('P');
        el.innerHTML = prod[i].name;

            $('#app').append(el);
        }
    })
}
document.addEventListener('load', drawPage());
Allan
  • 12,117
  • 3
  • 27
  • 51
James
  • 35
  • 7

2 Answers2

0

You need to rewrite the comparing function to sort your objects array by product name.

Prototype:

function drawPage() {
    $.get('/products', function (data) {
        console.log(data);
        var prods = data.products;

        //sorting by product names
        prods.sort(function(a, b){
          var x = a.name.toLowerCase();
          var y = b.name.toLowerCase();
          if (x < y) {return -1;}
          if (x > y) {return 1;}
          return 0;
        });

        for(var i=0; i<prods.length; i++){
           var el = document.createElement('P');
           el.innerHTML = prods[i].name;
           $('#app').append(el);
        }
    })
}
document.addEventListener('load', drawPage());

You can also sort the json directly before importing it in your array via: Sort JSON by value

Allan
  • 12,117
  • 3
  • 27
  • 51
  • If im using a button in my html which can toggle between sorted and unsorted. would i just create a new function function sorting() { and include the sorting code? Or would i have to somehow include it all and link it back to html all within my one function? – James May 20 '19 at 02:19
  • @James: Then you need to save the state of the button (a bool would be enough) and do the sorting or not depending on the value of that boolean. Each time the user click on the button you change its value – Allan May 20 '19 at 02:22
0

var prod = [
{name: "truck", price: "20000"},
{name: "car", price: "50000"},
{name: "bus", price: "30000"}]

function SortByName(x,y) {
      return ((x.name == y.name) ? 0 : ((x.name > y.name) ? 1 : -1 ));
}
$(function () {
        prod.sort(SortByName);
        console.log(prod)
    });
   
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
Rim Vo
  • 22
  • 2