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);
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 object of objects by property value (passing by tuples)
In vanilla JS use Object.entries
:
const data = {FR: {total: 875, min: 4, cutValue: 56},DE: {total: 478, min: 50, cutValue: 5},UK: {total: 1505, min: 0, cutValue: 0},PO: {total: 2995, min: 0, cutValue: 4},IT: {total: 1840, min: 10, cutValue: 3},ES: {total: 629, min: 30, cutValue: 33},};
let result = Object.entries(data).sort((a, b) => b[1].total - a[1].total);
console.log(result);
Sorting object properties by property value
An object does not (always) follow the insertion order. So it can't be guaranty that you always get same output. For sorting you can use either array or Map to maintain the order. For more info please see stackoverflow discussion.
According to question: var objs = {'1':2, '2':3, '3':1, '4':2};
How can I sort them by the value of numbers in JavaScript? You can do as follows
var objs = {
'1': 2,
'2': 3,
'3': 1,
'4': 2
};
var map = new Map(Object.entries(objs));
var sorted = new Map(Array.from(map).sort((a, b) => a[1] - b[1]));
console.log(sorted);
Sorting arrays numerically by object property value
Use Array.prototype.sort(), eg
myArray.sort((a, b) => a.distance - b.distance)
The sort()
method accepts a comparator function. This function accepts two arguments (both presumably of the same type) and it's job is to determine which of the two comes first.
It does this by returning an integer
- Negative (less-than zero): The first argument comes first
- Positive (greater-than zero): The second argument comes first
- Zero: The arguments are considered equal for sorting
When you're dealing with numeric values, the simplest solution is to subtract the second value from the first which will produce an ascending order result.
How to sort objects by value
let obj = {a: 24, b: 12, c:21, d:15};
// Get an array of the keys:
let keys = Object.keys(obj);
// Then sort by using the keys to lookup the values in the original object:
keys.sort(function(a, b) { return obj[a] - obj[b] });
console.log(keys);
Related Topics
Is There a JavaScript/Jquery Dom Change Listener
Abort Ajax Requests Using Jquery
How to Return Many Promises and Wait For Them All Before Doing Other Stuff
How Does Data Binding Work in Angularjs
Resolve Promises One After Another (I.E. in Sequence)
How to Detect Idle Time in JavaScript
Passing Data to a Bootstrap Modal
How to Get Started With Node.Js
Enter Data into a Custom-Handled Input Field
What's the Meaning of "=≫" (An Arrow Formed from Equals & Greater Than) in JavaScript
Simplest Code For Array Intersection in JavaScript
Check Variable Equality Against a List of Values
How to Do String Interpolation in JavaScript
Generate Random String/Characters in JavaScript
What Does the Construct X = X || Y Mean