Skip to content Skip to sidebar Skip to footer

Sorting Json Data Based On A Field

I have a Json data that I need to sort before display it. My Json is as below. I need to sort them based on the ColumnLocation. [{ 'Name': 'PieChart', 'Id': '1', 'ColumnLocat

Solution 1:

No need for lodash/underscore. You can use Array.prototype.sort: Since your values are strings, you must first parse them into numbers and then compare:

let a = [{"Name":"PieChart","Id":"1","ColumnLocation":"0","RowLocation":"0"},{"Name":"Calendar","Id":"2","ColumnLocation":"1","RowLocation":"0"},{"Name":"FavouriteFilter","Id":"3","ColumnLocation":"2","RowLocation":"0"},{"Name":"FilterResults","Id":"4","ColumnLocation":"0","RowLocation":"1"},{"Name":"Watched","Id":"5","ColumnLocation":"1","RowLocation":"1"}]

let sorted = a.sort((a, b) => parseInt(a.ColumnLocation) - parseInt(b.ColumnLocation));

console.log(sorted);

Solution 2:

Short and sweet.

let arr = [{"Name":"PieChart","Id":"1","ColumnLocation":"0","RowLocation":"0"},{"Name":"Calendar","Id":"2","ColumnLocation":"1","RowLocation":"0"},{"Name":"FavouriteFilter","Id":"3","ColumnLocation":"2","RowLocation":"0"},{"Name":"FilterResults","Id":"4","ColumnLocation":"0","RowLocation":"1"},{"Name":"Watched","Id":"5","ColumnLocation":"1","RowLocation":"1"}]

arr.sort ( ( a, b ) => { return parseInt ( a.ColumnLocation ) > parseInt ( b.ColumnLocation ) } );

console.log ( arr );

Note that if you don't convert to a number, the sorting can not be what you expect.


Solution 3:

Why not use _.sortBy ( http://underscorejs.org/#sortBy ) ?

var mysortedarray = _.sortBy(myarray, 'ColumnLocation');

Post a Comment for "Sorting Json Data Based On A Field"