首页 > 解决方案 > How to sort by name through Jquery?

问题描述

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());

标签: javascriptjquerysorting

解决方案


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>


推荐阅读