jquery - Load a JSON document and sort it on one or more values in key:value pairs with JavaScript -


i want load external json object , sort based on 1 or more key:value pairs. example using json below might need sort on category1 , type.

i've tried array.sort() no matter throw @ data never sorted; it's output in same order in json file.

{   "books": [     {       "sku": "{1234}",       "title": "moby dick",       "type": "paperback",       "category1": "fiction",       "category2": "classic",       "category3": "",       "image": "",       "ctalabel": "learn more"     },     {       "sku": "{5678}",       "title": "1984",       "type": "hardcover",       "category1": "fiction",       "category2": "",       "category3": "",       "image": "",       "ctalabel": "learn more"     },     {       "sku": "{5678}",       "title": "another title",       "type": "paperback",       "category1": "nonfiction",       "category2": "youngadult",       "category3": "",       "image": "",       "ctalabel": "learn more"     }   ] } 

 

$(function() {     $.getjson('books.json', function (data) {         console.log(data);         var items = data.books.map(function (item) {             return item.sku + ': ' + item.title;         });         if (items.length) {             var content = '<li>' + items.join('</li><li>') + '</li>';             var list = $('<ul />').html(content);             $("#show-data").html(list);         }     }); }); 

based on this answer, can implement multi-level sort follows :

function multilevelsort(arr, criteria) {     return arr.sort(function(x, y) {         return criteria.reduce(function(prev, curr) {             var dir = (curr.dir < 0) ? -1 : 1,                 x_ = x[curr.prop],                 y_ = y[curr.prop];             return prev || (x_ === y_ ? 0 : x_ > y_ ? dir : -dir);         }, 0);     }); } 

or, destructuring (in node not yet in browsers) :

function multilevelsort(arr, criteria) {     return arr.sort(function(x, y) {         return criteria.reduce(function(prev, {prop, dir}) {             dir = (dir < 0) ? -1 : 1;             var x_ = x[prop],                 y_ = y[prop];             return prev || (x_ === y_ ? 0 : x_ > y_ ? dir : -dir);         }, 0);     }); } 

where :

  • arr array of objects, in question.
  • criteria array of objects of following format :
var criteria = [     {prop: "type", dir: 1}, // dir:1=ascending; dir:-1=descending     {prop: "category1", dir: 1},      {prop: "category2", dir: 1}  ]; 

then call :

multilevelsort(myarray, mycriteria); 

like array.prototype.sort(), myarray mutated and returned.

demo


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -