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
Is there a way to sort/order keys in JavaScript objects?
Not within the object itself: the property collection of an object is unordered.
One thing you could do is use Object.keys()
, and sort the Array, then iterate it.
Object.keys(data)
.sort()
.forEach(function(v, i) {
console.log(v, data[v]);
});
Patches (implementations) for browsers that do not support ECMAScript 5th edition:
Object.keys
Array.forEach
Javascript sort object by key within nested objects
Anotner one sorting approach
const obj = {4:{1:[{order:1,name:'Test 4'}]},0:{15:[{order:7,name:'Test 1'},{order:3,name:'Test 3'},],12:[{order:1,name:'Test 2'}]}};
const result = Object.entries(obj).flatMap(([u1, v1]) =>
Object.entries(v1).flatMap(([u2, v2]) =>
v2.map((v3) => ({ key: u1*1_000 + u2 + v3.order/1_000, item: v3 }))
)
)
.sort(({ key: a }, { key: b }) => a - b)
.map(({ item }) => item);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }
Sort an array of object with key in JavaScript
Just this will work.
myArray.sort((a,b) => Object.entries(a)[0] < Object.entries(b)[0] ? -1 : 1);
Running example below:
const myArray = [
{ '2022-03-31': '32.2' },
{ '2022-04-01': '32.23' },
{ '2022-04-02': '32.9' },
{ '2022-03-30': '32.253' },
{ '2022-04-03': '32.253' },
{ '2022-03-18': '32.253' },
{ '2021-06-31': '32.37' }
];
myArray.sort((a,b) => Object.entries(a)[0] < Object.entries(b)[0] ? -1 : 1);
console.log(myArray);
Sorting Object of Object with sort and reduce function
Object keys order was not guaranteed earlier in JS. Now it is. But here is how it is going to be.
What matters here is for integer like keys, the order will be ascending.
For string keys it is order of insertion, which can be tested by appending a character to the integer every time.
let data={
"51": {"name": "text51"},
"54": {"name": "text54"},
"61": {"name": "text61"},
"64": {"name": "text64"},
"71": {"name": "text71"},
"74": {"name": "text74"},
"81": {"name": "text81"},
"84": {"name": "text84"}
};
let new_key=Object.keys(data).sort((a, b)=>parseInt(a.slice(-1)) - parseInt(b.slice(-1)));
let result=new_key.reduce((r, k) => {
console.log(r);
r['x-' + k] = data[k];
return r;
}, {});
Sort object keys/entries in specific order
You almost had it, the only issue is that you're not checking if sortOrder
actually contains the key you're iterating or not.
If you do sortOrder.indexOf(x)
but x
is not in sortOrder
, then indexOf
will return -1, explaining why the non-existent keys are always on top (--1 === +1). See reference for more info.
The fix is to manually put all keys that are not present in sortOrder
at the end of the array:
if (!sortOrder.includes(a)) return 1
if (!sortOrder.includes(b)) return -1
So in the end, you'd have this:
const ordered = Object.keys(data).sort((a, b) => {
if (!sortOrder.includes(a)) return 1
if (!sortOrder.includes(b)) return -1
return sortOrder.indexOf(a) - sortOrder.indexOf(b);
});
Related Topics
$(Document).Ready Equivalent Without Jquery
JavaScript by Reference Vs. by Value
How to Split a String, Breaking At a Particular Character
Is It an Anti-Pattern to Use Async/Await Inside of a New Promise() Constructor
How to Check If an Object Is an Array
Chrome/Firefox Console.Log Always Appends a Line Saying 'Undefined'
How to Enable Cors in Angularjs
How to Print a Circular Structure in a Json-Like Format
How to Add 30 Minutes to a JavaScript Date Object
What Do Parentheses Surrounding an Object/Function/Class Declaration Mean
How to Add a Delay in a JavaScript Loop
Send Post Data Using Xmlhttprequest
Why Is the Method Executed Immediately When I Use Settimeout
React Setstate Not Updating State
How to Check If an Object Has a Specific Property in JavaScript
Difference Between Call and Apply