Sorting a JSON array according one property in JavaScript

Morteza Asadi
1 min readSep 30, 2018

--

These days JavaScript is the foundation of very new technologies, Front-End frameworks, etc. One of the most commonly work in JavaScript is working with JSON arrays. In this article we’re going to sort an JSON array according a specific property.

Suppose we have a JSON array and we want to sort it by id or pId:

var items = [{id:2, title:"...", pId:62},
{id:1, title:"...", pId:43},
{id:4, title:"...", pId:74},
{id:9, title:"...", pId:35},
{id:5, title:"...", pId:81}];

To do this, write a function as below and call it in array.sort():

function sortByProperty(property){  
return function(a,b){
if(a[property] > b[property])
return 1;
else if(a[property] < b[property])
return -1;

return 0;
}
}

Final step is call above function in array.sort() :

items.sort(sortByProperty(“pId”)); //sort according to pId 

items.sort(sortByProperty(“id”)); //sort according to id

--

--