Sunday, 14 May 2017

Javascript: How to sort an array of records by values in one of the fields?

A straightforward approach


var sorted = [{a:0,b:0},{a:2,b:1},{a:1,b:2}].sort( function( a, b )
{
if ( a.a == b.a ) return 0;
return ( a.a > b.a ) ? 1 : -1;
}).reverse();

EDIT


And a more flexible approach


// Note: console.log() require Firebug
var records = [{a:0,b:0},{a:2,b:1},{a:1,b:2}];
console.log( records );
// Sorty by 'a' ascending
sortByProperty( records, 'a' );
console.log( records );
// Sort by 'b' descending
sortByProperty( records, 'b', true );
console.log( records );
function sortByProperty( arr, property, descending )
{
arr.sort( function( a, b )
{
return Boolean( descending )
? b[property] - a[property]
: a[property] - b[property]
} );
}

EDIT 2


A version that works for strings as well


// Note: console.log() require Firebug
var records = [
{a:0,b:0}
, {a:2,b:1}
, {a:'banana',b:'apple'}
, {a:1,b:2}
, {a:'apple',b:'banana'}
];
console.log( records );
// Sorty by 'a' ascending
sortByProperty( records, 'a' );
console.log( records );
// Sort by 'b' descending
sortByProperty( records, 'b', true );
console.log( records );
function sortByProperty( arr, property, descending )
{
arr.sort( function( a, b )
{
var c = a[property].toString()
, d = b[property].toString()
if ( c == d ) return 0;
return Boolean( descending )
? d > c ? 1 : -1
: d < c ? 1 : -1
} );
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...