Simple Function to Sort an Array of Objects

Simple function to sort an array of objects

How about this?

var people = [
{
name: 'a75',
item1: false,
item2: false
},
{
name: 'z32',
item1: true,
item2: false
},
{
name: 'e77',
item1: false,
item2: false
}];

function sort_by_key(array, key)
{
return array.sort(function(a, b)
{
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}

people = sort_by_key(people, 'name');

This allows you to specify the key by which you want to sort the array so that you are not limited to a hard-coded name sort. It will work to sort any array of objects that all share the property which is used as they key. I believe that is what you were looking for?

And here is a jsFiddle: http://jsfiddle.net/6Dgbu/

Sorting an array of objects by property values

Sort homes by price in ascending order:

homes.sort(function(a, b) {
return parseFloat(a.price) - parseFloat(b.price);
});

Or after ES6 version:

homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));

Some documentation can be found here.

For descending order, you may use

homes.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));

Sort array of objects by string property value

It's easy enough to write your own comparison function:

function compare( a, b ) {
if ( a.last_nom < b.last_nom ){
return -1;
}
if ( a.last_nom > b.last_nom ){
return 1;
}
return 0;
}

objs.sort( compare );

Or inline (c/o Marco Demaio):

objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0))

Or simplified for numeric (c/o Andre Figueiredo):

objs.sort((a,b) => a.last_nom - b.last_nom); // b - a for reverse sort

How to sort an object array by date property?

Simplest Answer

array.sort(function(a,b){
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b.date) - new Date(a.date);
});

More Generic Answer

array.sort(function(o1,o2){
if (sort_o1_before_o2) return -1;
else if(sort_o1_after_o2) return 1;
else return 0;
});

Or more tersely:

array.sort(function(o1,o2){
return sort_o1_before_o2 ? -1 : sort_o1_after_o2 ? 1 : 0;
});

Generic, Powerful Answer

Define a custom non-enumerable sortBy function using a Schwartzian transform on all arrays :

(function(){
if (typeof Object.defineProperty === 'function'){
try{Object.defineProperty(Array.prototype,'sortBy',{value:sb}); }catch(e){}
}
if (!Array.prototype.sortBy) Array.prototype.sortBy = sb;

function sb(f){
for (var i=this.length;i;){
var o = this[--i];
this[i] = [].concat(f.call(o,o,i),o);
}
this.sort(function(a,b){
for (var i=0,len=a.length;i<len;++i){
if (a[i]!=b[i]) return a[i]<b[i]?-1:1;
}
return 0;
});
for (var i=this.length;i;){
this[--i]=this[i][this[i].length-1];
}
return this;
}
})();

Use it like so:

array.sortBy(function(o){ return o.date });

If your date is not directly comparable, make a comparable date out of it, e.g.

array.sortBy(function(o){ return new Date( o.date ) });

You can also use this to sort by multiple criteria if you return an array of values:

// Sort by date, then score (reversed), then name
array.sortBy(function(o){ return [ o.date, -o.score, o.name ] };

See http://phrogz.net/JS/Array.prototype.sortBy.js for more details.

Sort array of objects by single key with date value

You can use Array.sort.

Here's an example:

var arr = [{
"updated_at": "2012-01-01T06:25:24Z",
"foo": "bar"
},
{
"updated_at": "2012-01-09T11:25:13Z",
"foo": "bar"
},
{
"updated_at": "2012-01-05T04:13:24Z",
"foo": "bar"
}
]

arr.sort(function(a, b) {
var keyA = new Date(a.updated_at),
keyB = new Date(b.updated_at);
// Compare the 2 dates
if (keyA < keyB) return -1;
if (keyA > keyB) return 1;
return 0;
});

console.log(arr);

How to sort an array of objects by multiple fields?

You could use a chained sorting approach by taking the delta of values until it reaches a value not equal to zero.

var data = [{ h_id: "3", city: "Dallas", state: "TX", zip: "75201", price: "162500" }, { h_id: "4", city: "Bevery Hills", state: "CA", zip: "90210", price: "319250" }, { h_id: "6", city: "Dallas", state: "TX", zip: "75000", price: "556699" }, { h_id: "5", city: "New York", state: "NY", zip: "00010", price: "962500" }];
data.sort(function (a, b) { return a.city.localeCompare(b.city) || b.price - a.price;});
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sort JavaScript array of Objects based on one of the object's properties

There are 2 basic ways:

var arr = [{name:"ABC"},{name:"BAC"},{name:"abc"},{name:"bac"}];

arr.sort(function(a,b){
var alc = a.name.toLowerCase(), blc = b.name.toLowerCase();
return alc > blc ? 1 : alc < blc ? -1 : 0;
});

or

arr.sort(function(a,b){
return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
});

Be aware that the 2nd version ignore diacritics, so a and à will be sorted as the same letter.

Now the problem with both these ways is that they will not sort uppercase ABC before lowercase abc, since it will treat them as the same.

To fix that, you will have to do it like this:

arr.sort(function(a,b){
var alc = a.name.toLowerCase(), blc = b.name.toLowerCase();
return alc > blc ? 1 : alc < blc ? -1 : a.name > b.name ? 1 : a.name < b.name ? -1 : 0;
});

Again here you could choose to use localeCompare instead if you don't want diacritics to affect the sorting like this:

arr.sort(function(a,b){
var lccomp = a.name.toLowerCase().localeCompare(b.name.toLowerCase());
return lccomp ? lccomp : a.name > b.name ? 1 : a.name < b.name ? -1 : 0;
});

You can read more about sort here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort



Related Topics



Leave a reply



Submit