Sorting a JavaScript Object by Property Name

Sorting a JavaScript object by property name

UPDATE from the comments:

This answer is outdated. In ES6 objects keys are now ordered. See this question for an up-to-date answer

By definition, the order of keys in an object is undefined, so you probably won't be able to do that in a way that is future-proof. Instead, you should think about sorting these keys when the object is actually being displayed to the user. Whatever sort order it uses internally doesn't really matter anyway.

By convention, most browsers will retain the order of keys in an object in the order that they were added. So, you could do this, but don't expect it to always work:

function sortObject(o) {
var sorted = {},
key, a = [];

for (key in o) {
if (o.hasOwnProperty(key)) {
a.push(key);
}
}

a.sort();

for (key = 0; key < a.length; key++) {
sorted[a[key]] = o[a[key]];
}
return sorted;
}

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

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


Related Topics



Leave a reply



Submit