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
andb.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. Returning1
placesa
afterb
and-1
placesa
beforeb
.
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
:
const teachers=[{id:1,user:{id:10,image:"image.jgp"}},{id:3,user:{id:30,image:null}},{id:2,user:{id:20,image:"image.jgp"}},{id:4,user:{id:40,image:null}}];
const sorted = teachers.sort((a, b) => b.user.image === null ? -1 : 1)
console.log(sorted)
Related Topics
Seo Friendly Url Results in CSS Img and Js Not Working
Multiple Inputs With Same Name Through Post in PHP
How to Maintain a "Version For the Server" - With Only Config Files Changed, in Git
How to Find Where I Will Be Redirected Using Curl in PHP
How to Update Code That Uses the Deprecated Each() Function
When Do I Use the PHP Constant "PHP_Eol"
How to Prevent Browser Cache For PHP Site
How to Access PHP Variables in JavaScript or Jquery Rather Than ≪PHP Echo $Variable ≫
How to Create Friendly Url in PHP
How to Create a Pdo Parameterized Query With a Like Statement
Filter/Remove Rows Where Column Value Is Found More Than Once in a Multidimensional Array
How to Rename Uploaded File Before Saving It into a Directory
Finding Cartesian Product With PHP Associative Arrays
How to Get a Substring Between Two Strings in PHP
Reference: Why Are My "Special" Unicode Characters Encoded Weird Using Json_Encode