Sorting an Array of Objects by Property Values

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

Sorting object property by values

Move them to an array, sort that array, and then use that array for your purposes. Here's a solution:

let maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
let sortable = [];
for (var vehicle in maxSpeed) {
sortable.push([vehicle, maxSpeed[vehicle]]);
}

sortable.sort(function(a, b) {
return a[1] - b[1];
});

// [["bike", 60], ["motorbike", 200], ["car", 300],
// ["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]

Once you have the array, you could rebuild the object from the array in the order you like, thus achieving exactly what you set out to do. That would work in all the browsers I know of, but it would be dependent on an implementation quirk, and could break at any time. You should never make assumptions about the order of elements in a JavaScript object.

let objSorted = {}
sortable.forEach(function(item){
objSorted[item[0]]=item[1]
})

In ES8, you can use Object.entries() to convert the object into an array:

const maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};

const sortable = Object.entries(maxSpeed)
.sort(([,a],[,b]) => a-b)
.reduce((r, [k, v]) => ({ ...r, [k]: v }), {});

console.log(sortable);

Sorting an array of objects based on all of its property values

You need to apply the comparisons one after another, linked by the "or" (||) operator. The or operator will not process its second argument if the first one was found to be truthy, i. e. if it returned a value different from 0.

Comparing numbers is easiest accomplished by a simple subtraction. Strings can be compared with String.prototype.localeCompare():

const arr = [{name: "A",age: 22,rating: 5,satisfaction: 2},{name: "B",age: 25,rating: 7,satisfaction: 4},{name: "C",age: 22,rating: 9,satisfaction: 8}];

arr.sort((a,b)=>
b.age-a.age ||
b.rating-a.rating ||
b.satisfaction-a.satisfaction ||
b.name.localeCompare(a.name))

console.log(arr);

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

How to sort an array of objects by property?

const data = [
{ "name": "xyz", "email": "xyz@gmail.com", "score": 0 },
{ "name": "abc", "email": "abc@gmail.com", "score": 1 }
].sort((a, b) => b.score - a.score);
const table = document.createElement('table');
document.body.append(table);
const tr = document.createElement('tr');
table.append(tr);
for (const key of Object.keys(data[0])) {
const th = document.createElement('th');
th.textContent = key;
tr.append(th);
}
data.forEach(datum => {
const trB = document.createElement('tr');
table.append(trB);
Object.values(datum).forEach(value => {
const td = document.createElement('td');
td.textContent = value;
trB.append(td);
});
});

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

Order an array of objects by whether property exists

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