Sort Array of Objects by One Property

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

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 object on a property but keep the objects first for which property is missing

Logic is basic array sorting logic.

  • If both a.order and b.order are defined return 1 or -1 depending on the largest value.
  • If either one of them is undefined return 1 or -1 depending on the defined value.
  • Please Note: The value 1 and -1 determines the relative position between the two nodes. Returning 1 places a after b and -1 places a before b.

const testWidgetOrderSort = [
{ "_id": "name", "order": 1 },
{ "_id": "is", "order": 2 },
{ "_id": "my", "order": 0 },
{ "_id": "oh I would be very first" },
{ "_id": "adam", "order": 3 }
];
const output = testWidgetOrderSort.sort((a, b) => {
if( a.order !== undefined && b.order !== undefined ) {
return a.order > b.order ? 1 : -1;
} else {
return a.order !== undefined ? 1 : -1
}
});
console.log(output);

Sort array of objects by one property

Use usort, here's an example adapted from the manual:

function cmp($a, $b) {
return strcmp($a->name, $b->name);
}

usort($your_data, "cmp");

You can also use any callable as the second argument. Here are some examples:

  • Using anonymous functions (from PHP 5.3)

      usort($your_data, function($a, $b) {return strcmp($a->name, $b->name);});
  • From inside a class

      usort($your_data, array($this, "cmp")); // "cmp" should be a method in the class
  • Using arrow functions (from PHP 7.4)

      usort($your_data, fn($a, $b) => strcmp($a->name, $b->name));

Also, if you're comparing numeric values, fn($a, $b) => $a->count - $b->count as the "compare" function should do the trick, or, if you want yet another way of doing the same thing, starting from PHP 7 you can use the Spaceship operator, like this: fn($a, $b) => $a->count <=> $b->count.

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

JavaScript array of objects sort by specific property and then group by custom priority values

You can do this easily without lodash too.

You can use a customized sort function when calling the sort() function of an array. Create a sort string including a 0 for online users and a 1 for offline users followed by the name. Then use this sort string in the comparison.

let users = [{
'name': 'C',
'status': 'online'
},
{
'name': 'd',
'status': 'online'
},
{
'name': 'a',
'status': 'offline'
},
{
'name': 'b',
'status': 'online'
},
{
'name': 'f',
'status': 'offline'
},
{
'name': 'e',
'status': 'offline'
}
];

users.sort((a, b) => {
let sortStringA = (a.status.toUpperCase() == 'ONLINE' ? 0 : 1) + a.name.toUpperCase();
let sortStringB = (b.status.toUpperCase() == 'ONLINE' ? 0 : 1) + b.name.toUpperCase();
if (sortStringA < sortStringB) {
return -1;
}
if (sortStringA > sortStringB) {
return 1;
}
return 0;
});

console.log(users);

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; }

Order an array of objects by whether property exists

You can use Array.sort and check whether the image property is null: